Code9090
Code9090

Reputation: 21

.ToString Gives an error but Convert.ToString works fine why?

in my c# code i try to write like

 public string instancePath = (HttpContext.Current.Application["InstancePath"]).ToString();

But when i create the object of this class then it does not works ,it throws an exception. But when i use public string instancePath = Convert.ToString(HttpContext.Current.Application["InstancePath"]); it works perfectly, Why convert.ToString() works insted of ToString()? any help will be appreciated

thanks in advance

Upvotes: 1

Views: 657

Answers (2)

Arunprasanth K V
Arunprasanth K V

Reputation: 21931

ToString() needs to exist to call an instance method on it. It does not handle any null value. This means that on an object it presumes that the object is not null. However, when we use Convert.ToString(obj) it handles null values too. It returns empty if it is null.

Upvotes: 3

SanyTiger
SanyTiger

Reputation: 666

Try

string str = HttpContext.Current.Application["InstancePath"] as string;

Upvotes: 2

Related Questions