Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value directly to class variable

Tags:

c#

I don't know if this is that easy nobody is looking for that, but I didn't found anything...

I want to do the following:

public class foo
{
    string X 
    {
        get; 
        set
        { 
            //set and do some other stuff 
        }
    }

    //some other functions
}

Main:

private foo = new foo();

foo = "bla";

How can I assign this bla DIRECTLY to the class-variable foo without using foo.X = "bla"?

How are the datatypes doing this, e.g string? How are they made? Because I can do string y; y = "abc" ?

like image 289
Dominik Avatar asked Jan 11 '17 09:01

Dominik


People also ask

How do you assign a value to a class variable in Python?

Use dot notation or setattr() function to set the value of class attribute. Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime. Python stores class variables in the __dict__ attribute.

Can you assign a value to a variable?

Assigning values to variables is achieved by the = operator. The = operator has a variable identifier on the left and a value on the right (of any value type). Assigning is done from right to left, so a statement like var sum = 5 + 3; will assign 8 to the variable sum .

Can we assign value in class in C++?

The C++ compilers calls a constructor when creating an object. The constructors help to assign values to class members.


Video Answer


1 Answers

Are you looking for implicit operator?

public class foo {
  string X {
    get;
    set;
  }

  public static implicit operator foo(string value) {
    return new foo() {
      X = value
    };
  }
}

Please, notice, that there's no constructor call here which will be called (and thus create a new foo instance) implicitly:

private foo myFoo = "bla";
like image 67
Dmitry Bychenko Avatar answered Oct 19 '22 17:10

Dmitry Bychenko