3

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.

14
  • 3
    If you want that level of control, then you're probably going to have to use a class instead of a struct. Commented May 24, 2018 at 10:50
  • 1
    @DavidG you're right, it would be dead-simple if it could be a class. However, since it will be used for P/Invoke it needs to be a struct. Commented May 24, 2018 at 10:51
  • 1
    It's kind of XY problem, it would be great if you add some more details about your question and why you want to do such thing. Commented May 24, 2018 at 10:59
  • 1
    It won't really solve all problems, because struct can be initialized to default state without calling that constructor. And if that state is unacceptable to you - you have to verify manually then (obsolete constructor will not catch all problem cases). Commented May 24, 2018 at 11:02
  • 1
    You can use a class for P/Invoke - what makes you think you can't? It gets marshalled by the marshaller either way. Unless it's a struct embedded in another struct. Commented May 24, 2018 at 11:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.