'Creating Variables By string text
I am looking to create variables by string value. Is there smarter way to do it?
if (str == "DateTime")
{
DateTime d = new DateTime();
}
else if( str == "TimeSpan")
{
TimeSpan s = new TimeSpan();
}
I want to write something like that:
object o = new someString() ` when someString is "DateTime" or "TimeSpan"`
Solution 1:[1]
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.
Solution 2:[2]
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");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kisar |
| Solution 2 | SDHEER |
