#User-defined explicit and implicit conve...
1 messages · Page 1 of 1 (latest)
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!
Ah, ok, you said you were coming from typescript?
Ha, sall good, sir I guess
But its a good language move from TS to C#, same guy designed both
Oh, cool! I didn't know
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
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,
};```
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
Ok thanks, I'll dive into it
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;
}
I see. Ok I am learning about structs now and the difference between value semantics and reference semantics. Thanks for your help!
No problem, feel free to hit me up if you have anymore questions