Cool Blue Cool Blue - 1 month ago 11
C# Question

typeof cannot resolve symbol

In the following class I get a compile error on

typeof
.

Why can't the compiler resolve the type?

public class TestTypeOf
{
public struct Teststruct
{
public int d1;
public int d2;
}
Teststruct cds;

public Teststruct ToString (IntPtr lParam)
{
var t = typeof(cds); // cannot resolve symbol 'cds'
cds.d1 = 1;
cds.d2 = 2;
return cds;
}

public TestTypeOf ()
{
cds = new Teststruct();
}

}

Answer

The typeof operator works with types directly at compile time. For instance typeof(DateTime). If you want the type of an object, use the GetType() method. It derives from Object, so it will be available on any object.

var hello = "Hello, world!";
var type = hello.GetType();