Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Restricting Types in method parameters (not generic parameters)

I'd like to code a function like the following

public void Foo(System.Type t where t : MyClass)
{ ... }

In other words, the argument type is System.Type, and I want to restrict the allowed Types to those that derive from MyClass.

Is there any way to specify this syntactically, or does t have to be checked at runtime?

like image 308
kpozin Avatar asked May 20 '09 03:05

kpozin


People also ask

What is\\ C?

\c means you are escaping the "c" character, allowing you to print c \c means you are escaping the "\" character, which allows you to print \c. Escaping a character means that you are making the compiler ignore the character, if it is used for any functions or is reserved within a string.

What C is used for?

C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


3 Answers

If your method has to take a Type type as it's argument, there's no way to do this. If you have flexibility with the method call you could do:

public void Foo(MyClass myClass)

and the get the Type by calling .GetType().

To expand a little. System.Type is the type of the argument, so there's no way to further specify what should be passed. Just as a method that takes an integer between 1 and 10, must take an int and then do runtime checking that the limits were properly adhered to.

like image 82
Timothy Carter Avatar answered Oct 23 '22 13:10

Timothy Carter


Specifying the type be MyClass, or derived from it, is a value check on the argument itself. It's like saying the hello parameter in

void Foo(int hello) {...}

must be between 10 and 100. It's not possible to check at compile time.

You must use generics or check the type at run time, just like any other parameter value check.

like image 25
Colin Burnett Avatar answered Oct 23 '22 13:10

Colin Burnett


You can use the following:

public void Foo<T>(T variable) where T : MyClass
{ ... }

The call would be like the following:

{
    ...
    Foo(someInstanceOfMyClass);
    ...
}
like image 36
Pat Avatar answered Oct 23 '22 13:10

Pat