#User-defined explicit and implicit conve...

1 messages · Page 1 of 1 (latest)

naive jolt
#

Hmm the first of those options seems easier to wrap my head around. I don't even know what a struct is yet, so reading that doc about implicit / explicit conversions seems out of my league for now. Thanks!

runic vector
#

Ah, ok, you said you were coming from typescript?

naive jolt
#

Yessir

#

or m'aam

runic vector
#

Ha, sall good, sir I guess

#

But its a good language move from TS to C#, same guy designed both

naive jolt
#

Oh, cool! I didn't know

runic vector
#

Yeah, think he's still at MS, but he's part of the language spec team for both,

#

Anyway, a few parts of C# are pretty directly analogous to some TS/JS bits,
As for structs, if it helps, think of them like an object that is treated the same way as primitive types are, its copied instead of referenced, and be treated a lot of the same ways

naive jolt
#

So with this schema:

class BaseClass {
  public string foo,
  public string bar
}

class TypeA : BaseClass {
  public int baz
}

class TypeB : BaseClass {
  public int bazTimes2
}

How can I avoid the same problem of:

TypeA myTypeA = new() {
  foo = 'foo',
  bar = 'bar',
  baz = 1
}

TypeB myTypeB = new() {
  foo = myTypeA.foo,
  bar = myTypeA.bar,
  baz = myTypeA.baz * 2
}

When the only thing thats actually different or interesting is the baz property?

#

In Typescript you could do:

TypeB myTypeB = {
  ...myTypeA,
  bazTimes2 = myTypeA.baz * 2
}```
#

Heres the actual code that is generating this question, you can see it's starting to get cumbersome:

ParsedToadPiggy newPiggy = new() {
  currentHunger = piggyData.currentHunger,
  from = ToVector3(piggyData.from),
  to = ToVector3(piggyData.to),
  next = ToVector3(piggyData.next),
  memIdentifier = piggyData.memIdentifier,
  moveSpeed = piggyData.moveSpeed,           totalFoodDesired = piggyData.totalFoodDesired,
};```
runic vector
#

So, I think your best bet would actually be to just write this once for the conversion operator, I know it seems complex, but operator is pretty much just like Symbol in TS, it just signifies a method is for a particular system-level reason instead of just a normal method

naive jolt
#

Ok thanks, I'll dive into it

runic vector
#
TypeA 
{
  public int a;
  public int b;
  // Static just means its attacked to the TypeA class "object" instead of an instance of TypeA
  public static implicit TypeB(TypeA a) => new TypeB() { a = a.a, b = b.b };
}
#

Its not too bad, its basically just wrapping your conversion logic into a properly named method, its like JS:

var thing = { 
  [Symbol.Iterator]: () => whatevs; 
}
naive jolt
#

I see. Ok I am learning about structs now and the difference between value semantics and reference semantics. Thanks for your help!

runic vector
#

No problem, feel free to hit me up if you have anymore questions