Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# initialization question

This might be lame, but here:

public interface Interface<T>
{
    T Value { get; }
}

public class InterfaceProxy<T> : Interface<T>
{
    public T Value { get; set; }
}

public class ImplementedInterface: InterfaceProxy<Double> {}

Now I want to create an instance of the ImplementedInterface and initialize it's members.

Can this be done somehow like this (using initialization lists) or the same behavior can only be achieved using the constructor with Double argument?

var x = new ImplementedInteface { 30.0 };
like image 974
Yippie-Ki-Yay Avatar asked Dec 07 '10 16:12

Yippie-Ki-Yay


Video Answer


3 Answers

Can be done by:

var x = new ImplementedInteface { Value = 30.0 };
like image 168
Saeed Amiri Avatar answered Sep 21 '22 23:09

Saeed Amiri


var x = new ImplementedInterface() { Value = 30.0 };
like image 25
Marcel Gheorghita Avatar answered Sep 22 '22 23:09

Marcel Gheorghita


The only way to achieve what you're after is if your class implements IEnumerable<T> and has an Add method:

public class MyClass : IEnumerable<double>
{
   public void Add(double x){}
}

Then you can do:

MyClass mc = new MyClass { 20.0 };

Obviously that's not what you want, because that doesn't set your Value and it allows you to add multiple values:

MyClass mc = new MyClass { 20.0, 30.0 , 40.0 };

Just go with the standard object initializes like others have pointed out:

var x = new ImplementedInterface() { Value = 30.0 };
like image 45
BFree Avatar answered Sep 21 '22 23:09

BFree