0

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"`
3
  • 4
    what is the purpose behind that? looks like a xy-problem Commented Mar 17, 2022 at 7:10
  • you should be aware that even if that were possible - which it is technically - Os type will allways be just object. So you can't do much with it. You'd have to cast it to the underlying runtime-type, which you don't know at compile-time. Commented Mar 17, 2022 at 7:16
  • What value does a default DateTime value actually have? Not as in "what is the value of the object" but more like "what do you intend to do with it, how is this useful for your program"? Same with TimeSpan, in both cases they will sort of have a "zero" value, or some default low value. I just don't see what you intend to do with these. Commented Mar 17, 2022 at 7:53

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

hi I have oracle Table that one column represents type in c# And I want to dynamically assign variables by the text in my column. Without the need of refactoring my c# code hope I'm understandable thanks
How are you using the variables afterwards? Do you store them as a DateTime/TimeSpan within an object? Do you store them in a List<object> where you have a mix of DateTimes and TimeSpans? So in essence, do you need the variables to be proper DateTimes or TimeSpans or will you need them as objects?
Objects its fine and do the works
0

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");
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.