-3

Is there a way to pass an anonymous struct to an object constructor in C#?

I am using the struct for deserializing JSON from within the new object.

public class MyClass
{
    public MyClass (List<object> NewObjects, ?anonymousStruct?)
    {
        NewObjects.Add (JsonConvert.DeserializeObject< anonymousStruct > (JsonString));
    }
}

EDIT: To Clarify -> I wish to pass different kinds of structs into the class depending on what I need to deserialise, so I can't specify the struct ahead of time. The information is deserialised into the struct type and inserted into the list of objects.

songololo
  • 4,724
  • 5
  • 35
  • 49

3 Answers3

3

I am not exactly sure what you are trying to accomplish, but from the usage with a generic Deserializer it seems that generic class with type argument restricted to struct may be exactly what you need:

public class MyClass<TStruct> 
      where TStruct : struct
{
    public MyClass (List<object> NewObjects)
    {
        NewObjects.Add (JsonConvert.DeserializeObject<TStruct>(JsonString));
    }
}
Community
  • 1
  • 1
Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53
2

Ok, I think there may be some form of misunderstanding. A struct is a value-type that you define. As such, you can specify one as a parameter by declaring it as such (for a declared class constructor:)

public MyClass(MyStructType structVal)
{
    ...
}

Since a struct is a value-type, it will always be initialized.* However, if you want to be able to pass a null reference to your constructor, just add a query right after the struct-type name:

public MyClass(MyStructType? structVal)
{
    ...
}

This means you can now instantiate your MyClass as such:

MyClass instance = new MyClass(null);

The structVal parameter will be null and can be handled as such. If your class absolutely needs a struct instance, you may need to create some way of defining a new struct as being in an uninitialized state.

[*] To be clear, a struct may contain reference type object that may be null (string objects, for instance) however, the reference to your struct will always be initialized once you define one in your code.

RLH
  • 15,230
  • 22
  • 98
  • 182
1

default(MyStruct) is the construct you are looking for - default.

var my = new MyClass (NewObjects, default(TemplateStruct));

Note that using generic method/class is better (as shown in other answers), but if your class must be non-generic than passing sentinel object is an option to pass type.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179