Home > database >  C#: default value for Vector in constructor
C#: default value for Vector in constructor

Time:01-19

I have the following problem: I have a classs that takes a position as a Vector2 in its constructor. Now, in some cases I don't know the position and want to change it at another place in the code. Since you can't make a Vector2 = null in C#, is there any default value for a Vector2 to signalize: "This Vector has no Value"?

This is the constructor in question:

public SoundEvent(SoundEffects sound, Vector2 soundOrigin)

I want to be able to call this constructor either with the SoundEffect only, or with the SoundEffect and position.

CodePudding user response:

This is a better way:

public SoundEvent(SoundEffects sound, Vector2? soundOrigin = null)
   Vector2 so;
   if (soundOrigin == null)
      so = new Vector2(); // default to origin?
    else
      so = soundOrigin;

The extra variable so guarantees null uses will not throw errors later.

CodePudding user response:

Nullable<Vector2> is what I was looking for.

  • Related