Fi Jeleva
Fi Jeleva

Reputation: 63

Initializing obj with/without default values

In c#:

public class SomeClass 
{
   int x;
   int y;
SomeClass (int x, int y)
{
  this.x = x;
  this.y = y;
}
}

Is there easy way to make new SomeClass without setting x and y instead to have default values for them and if I set values to set them else to have the default values?

Upvotes: 0

Views: 78

Answers (5)

Amit Kumar Singh
Amit Kumar Singh

Reputation: 4475

A default constructor would do that automatically. You can use optional parameters in the constructor.

Read more on named and optional parameters.

public class SomeClass
{

    // You can also write this as 
    // public SomeClass(int x=default(int), int y=default(int)) if you do 
    // not want to hardcode default parameter value.
    public SomeClass(int x=0, int y=0)
    {
        this.X = x;
        this.Y = y;
    }
}

You can call it as

 void Main()
{
    SomeClass a = new SomeClass();

    SomeClass b = new SomeClass(1);

    SomeClass c = new SomeClass(2,4);

}

Upvotes: 0

Ian H.
Ian H.

Reputation: 3919

Use a parameterless constructor.

Since the instances have to be created somehow using a new keyword, you can use a parameterless constructor inside your class.

public SomeClass ()
{
    x = 0;
    y = 0;
}

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

Sure, with C#6 you can use auto-implemented properties:

public class SomeClass
{
    public int X { get; } = 123;
    public int Y { get; } = 456;

    public SomeClass(){ }

    public SomeClass(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }
}

Of course you need a parameterless constructor.

If you instead mean default values of the type, that is done automatically(0 for numerical types).

Upvotes: 4

David
David

Reputation: 218827

Sure...

new SomeClass(default(int), default(int))

Or, more simply:

new SomeClass(0, 0)

The default value for int is always 0. So even if you define it with a parameterless constructor:

public SomeClass() { }

Those int class members would still default to 0.

Upvotes: 2

Christos
Christos

Reputation: 53958

You need to define a parameterless constructor:

public class SomeClass 
{
   int x;
   int y;

   public SomeClass {}
   public SomeClass (int x, int y)
   {
       this.x = x;
       this.y = y;
    }
}

When you create an object like:

var someClass = new SomeClass();

both x and y would be initialized using their default values, which is 0.

If you don't want to do so, you could handle this by passing to the constructor that you have already declared the default values of x and y, as already David has pointed out.

Upvotes: 1

Related Questions