简体   繁体   中英

Is there a C# equivalent to python's type() function?

I am learning C# and have a very basic background in Python where I was familiar with the type() function where the data type of a variable can be returned via:

type(myVariable)

Is there a C# equivalent to this function?

I am asking in the context of wanting to use such a function on a C# variable that has been created using var eg:

var myNewVariable = "Hello!"

I am using explicit data types in general eg:

string myNewString = "Hello!"

But I am just wondering what data type a variable created using var defaults to and thought something similar to type() would be a good way to check out what was happening ' under the hood ` so to speak.

You can try using GetType() method:

Type myType = myVariable.GetType();

For instance

String typeName = "My String".GetType().Name; // <- "String"

You have couple of options here

  1. typeof. typeof takes a type name (which you specify at compile time).
  2. GetType gets the runtime type of an instance.

Example

B a = new B();
a.GetType() == typeof(B) 

Note: a is an instance of an object B . Whereas B is a type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM