Search code examples
c#structattributesdefault-constructor

Attribute on struct default constructor


As structs cannot have explicit user-defined parameterless constructors e.g.

public struct MyStruct
{
    public MyStruct() { … } // Not allowed!
}

I was wondering if and how I can apply an attribute to that exact constructor. In the end, what I want to do is this (best would be if the parameterless constructor could be private, but that's not allowed either):

public struct MyStruct
{
    [Obsolete("Do not call the constructor directly, use MyStruct.Get() instead.")]
    public MyStruct() { … }

    public static MyStruct Get
    {
      // Important initializing here.
    }
}

Is there something like this fictional attribute target [constructor: Obsolete()] which allows for an attribute to be applied to the default constructor?

EDIT: Some more information.

The situation is this: I need to use MyStruct for P/Invoke and cannot use a class. I want to warn the user that they shouldn't get an instance of MyStruct because it misses important initialization, and they should rather use a factory method instead.


Solution

  • Because of struct is a ValueType, by its nature you can't find any way.

    even you instantiated a struct or not, it will be instantiated.

    int x = new int(); is equivalent to int x;

    and

    MyStruct s = new MyStruct(); is equivalent to MyStruct s;

    Suppose you can find a way to warn about MyStruct s = new MyStruct();. any definition to MyStruct s; is also warned! Then there is no way.