Jeyhun
Jeyhun

Reputation: 469

How should I declare that my method require any class?

When Method require any string we write that

void method(string str)
{
str="OK";
}

I have a method that require any class. Little part of my method:

Void Post()
{
responsefromserver = new JavaScriptSerializer.Deserialize<T>(sr.ReadToEnd());
}

T-must be any class. But I don't know how should I declare that my method require any class ?

Upvotes: 2

Views: 65

Answers (3)

L-Four
L-Four

Reputation: 13541

Make it generic:

void Post<T>()
{
    responsefromserver = new JavaScriptSerializer.Deserialize<T>(sr.ReadToEnd());
}

And then use it like:

 Post<YourClass>();

You can constraint your generic method if needed.

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

Make your method generic and add generic parameter constraint:

void Post<T>()
   where T: class
{
    responsefromserver = new JavaScriptSerializer.Deserialize<T>(sr.ReadToEnd());
    // ...
}

You can parametrize it with any class:

Post<FooClass>(); // OK if FooClass is a class
Post<int>(); // fail, because integer is a value type

Upvotes: 3

sll
sll

Reputation: 62544

You just inject dependency as a parameter or in your case - better to inject deserializer, and probably not on the Post() method level but on a class constructor level then reuse in Post().

Upvotes: 0

Related Questions