I am trying to store the value from an object into a string variable. If the object is null , it will shows an error "object reference not set to an instance of an object". If I try to store the value from SupPhone.PhoneNumber into a string variable and if it has the value, it would be working fine. But if SupPhone.PhoneNumber is coming as null then it will throw an error "object reference not set to an instance of an object". Here is the code
[(XMLType="CustRec"),XMLRoot,Serializable]
public class SupPhone
{
private string _phone
}
public SupPhone()
{
_phone = string.empty;
}
[XMLElement(ElementName="PHONE_NUMBER"]
public string PhoneNumber
{
get{ return _phone}
set{_phone = value}
}
program.cs
SupPhone suphone = phonecollection.GetMainPhone
// Here how can I give if suphone is null to set empty string. I tried to give
if(suphone.Tostring()==null) it doesnot work,
I am using .net7 so ternary operator will not work//
string phonenbr = suphone ;
isvalidphone() // if the value is null here error will throw
public SupPhone GetMainPhone()
{
get
{
SupPhone mainphone = null
for (int a=0; a<base.count; a++)
{
mainphone = base[x]
}
}
return mainphone
}
bool isvalidphone(string phone )
{
}
>Solution :
You could check the suphone variable itself first:
if(suphone == null)
{
suphone = String.Empty;
}
string phonenbr = suphone;
Or
string phonenbr = (string)(suphone ?? string.Empty);