Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

value to string is set to null irrespective of the condition in c#

I am assigning a value to var in c#

string fileName  = properties.AfterProperties["Name"] != null ? properties.AfterProperties["Name"].toString(): "";

Now the problem i face is fileName is null irrespective of the value of properties.AfterProperties["Name"]

I checked value of properties.AfterProperties["Name"] which had fileName and i also checked the entire assignment statement in the immediate window and it assigning the value of properties.AfterProperties["Name"] to the fileName

But when i press f11 after that assignment line, the value of fileName is null!!

Upvotes: 2

Views: 66

Answers (3)

Rajeshkumar Kandhasamy
Rajeshkumar Kandhasamy

Reputation: 6461

You may try this as well

string fileName  = properties.AfterProperties["Name"] != null && !String.IsNullOrEmpty(properties.AfterProperties["Name"].toString()) ? properties.AfterProperties["Name"].toString(): "";

By the way small hint:

properties.AfterProperties["Name"] != null // This check avoids object reference errors.

!String.IsNullOrEmpty(properties.AfterProperties["Name"].toString()) // This check will avoid your problem - returning empty instead of null.

Hope this helps.

Upvotes: 2

NeverHopeless
NeverHopeless

Reputation: 11233

May be trying like this:

string fileName = !properties.AfterProperties["Name"].Equals(null) ? properties.AfterProperties["Name"].toString(): "";

Upvotes: 1

Fabio
Fabio

Reputation: 11990

It depends on the type of AfterProperties.

In the first condition you used properties.AfterProperties["Name"], but in the assignment you used properties.AfterProperties["Name"].ToString()

Maybe properties.AfterProperties["Name"] is not null but properties.AfterProperties["Name"].ToString() returns null.

Upvotes: 1

Related Questions