+ 1
Create an anything struct?
I am just doing an experiment if a struct could handle different types in one property. Is there an alternativ for the var keyword? https://code.sololearn.com/cUU97Z0RrNKj/?ref=app
3 Antworten
+ 1
Correct! But switching types on the fly is not something you are supposed to do in languages like C#.
Now, C# has `dynamic`, like
struct egal {
public dynamic save;
}
which does what you want but it completely disables the typechecker which can lead to many bugs.
There are usecases for `dynamic` - for example you read a json file in C# and you don't know how it looks like before you read it.
But most of the time generics are a better choice!
0
You've discovered generics :)
struct egal<T> {
public T save;
}
egal<bool> myegal = new egal<bool>();
Alternatively you can read up on the `dynamic` keyword which can handle different types but that should be used with caution.
0
I didn't know generics yet, but on the first look I'd guess they can't accept different types after initialisation?