JSArrakis JSArrakis - 1 year ago 73
C# Question

C# Error when attempting to pass Type as parameter when method requires a type

As a test case Ive created the following very simple method:

public static object TestMethod(Type t)
return t;

For the type I am attempting to pass through it, I have created a very basic class also as a test:

public class TestClass
public string name { get; set; }

Finally I am attempting to call the method normally:

TestClass sample = TestMethod(TestClass);

However it seems that when TestClass is passed as a parameter for
, I receive the error: "'TestClass' is a type, which is not valid in the given context."

This makes no sense to me as the parameter required IS a type.

Answer Source

To use your method, do it like this

TestClass sample = (TestClass)TestMethod(typeof(TestClass));

Your Result will be an Type and not TestClass so you will get a RuntimeException.

On already existing instances use


But what are your trying to achieve?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download