+ 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

26th Jul 2020, 12:03 PM
Stefan Nohn
Stefan Nohn - avatar
3 Answers
+ 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!
26th Jul 2020, 12:40 PM
Schindlabua
Schindlabua - avatar
0
You've discovered generics :) struct egal<T> { public T save; } egal myegal = new egal(); Alternatively you can read up on the `dynamic` keyword which can handle different types but that should be used with caution.
26th Jul 2020, 12:16 PM
Schindlabua
Schindlabua - avatar
0
I didn't know generics yet, but on the first look I'd guess they can't accept different types after initialisation?
26th Jul 2020, 12:23 PM
Stefan Nohn
Stefan Nohn - avatar