How can I get the data type of a variable in C#?

前端 未结 8 707
忘了有多久
忘了有多久 2020-11-27 04:32

How can I find out what data type some variable is holding? (e.g. int, string, char, etc.)

I have something like this now:

using System;
using System         


        
相关标签:
8条回答
  • 2020-11-27 05:35

    Generally speaking, you'll hardly ever need to do type comparisons unless you're doing something with reflection or interfaces. Nonetheless:

    If you know the type you want to compare it with, use the is or as operators:

    if( unknownObject is TypeIKnow ) { // run code here
    

    The as operator performs a cast that returns null if it fails rather than an exception:

    TypeIKnow typed = unknownObject as TypeIKnow;
    

    If you don't know the type and just want runtime type information, use the .GetType() method:

    Type typeInformation = unknownObject.GetType();
    

    In newer versions of C#, you can use the is operator to declare a variable without needing to use as:

    if( unknownObject is TypeIKnow knownObject ) {
        knownObject.SomeMember();
    }
    

    Previously you would have to do this:

    TypeIKnow knownObject;
    if( (knownObject = unknownObject as TypeIKnow) != null ) {
        knownObject.SomeMember();
    }
    
    0 讨论(0)
  • 2020-11-27 05:39

    Its Very simple

    variable.GetType().Name
    

    it will return your datatype of your variable

    0 讨论(0)
提交回复
热议问题