-9

How to check typeof parameters in method with help code contracts?

I need check type argument in method

Mediator
  • 14,951
  • 35
  • 113
  • 191
  • 1
    Do you mean the type of objects passed into your method or the types that are specified for generic parameters? – Guvante Jul 31 '13 at 16:35
  • Are you sure generics is not the way to go? – Mark Sowul Jul 31 '13 at 16:36
  • If you have requirements to the type of the arguments to a method, why aren't you simply writing the right type for the parameters to it to begin with? – Lasse V. Karlsen Jul 31 '13 at 16:37
  • 2
    As a mediator I would expect a better question. What have you tried? Have you tried `if (arg1.GetType() == typeof(SomeClass))`? – km1 Jul 31 '13 at 16:39
  • 3
    Are you asking the same question that you asked 30 min ago, just with less information this time? http://stackoverflow.com/questions/17975546/how-to-check-type-parameter – Rubixus Jul 31 '13 at 16:44

2 Answers2

3

How about

public void MyMethod(object parameter)
{
    if (parameter.GetType() == typeof(Int32))
    {
        //Do some stuff
    }
}

In continuation to your other question

class ManagerCar : IBlalba
{
    public void Render(IViewTemplate template)
    {
        if (template.GetType() == typeof(CarViewTemplate))
        {
            //Do some stuff
        }
    }
}
Community
  • 1
  • 1
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
0

I think this should do it:

Contract.Requires(yourParameter is YourType);

Although I have to say this sounds like a pretty bad idea, unless you're required to use underspecified types for interface implementation reasons.

Magnus Grindal Bakken
  • 2,083
  • 1
  • 16
  • 22