Home > Back-end >  Creating Variables By string text
Creating Variables By string text

Time:03-17

Im looking to create variables by string value, is there smarter way to do it then.

if (str == "DateTime")
{
        DateTime d = new DateTime();
}

else if( str == "TimeSpan")
{
        TimeSpan s = new TimeSpan();
}

extra extra...

I want to write something like that.

object o = new someString() ` when someString is "DateTime" or "TimeSpan"`

Thanks in advanced

CodePudding user response:

You can do something like this which does the same thing but more concisely:

object o = str switch
{
    "DateTime" => new DateTime(),
    "TimeSpan" => new TimeSpan(),
    _ => throw new NotImplementedException()
};

It would be helpful to know what you want to do with the variable afterwards, however, because there might be better ways if you provide context.

CodePudding user response:

May be you can use the dynamic variables, and check the type of it in runtime. eg:

dynamic str ;
        str = DateTime.Now.TimeOfDay;
        if(str.GetType()==typeof(System.TimeSpan))
        {
            Console.Write("hello");
        }

CodePudding user response:

As I Understood ,you basically want to write in one line linq query. right?

var data=str=="DateTime"?xyz:abc;

explanation:

xyz refers when str is equal to datetime

abc refers when not equals.

  • Related