简体   繁体   中英

Class with properties but few properties not assigned

I have c# class i have different properties.

public class Employee
{
    public int ID;
    public string Name;
    public int Age;
}

WebServices pp=new WebServices();

Employee emp= pp.GetEmpInfo(); 
//pp is an instance of webservices which is web referenced in the app.

emp.ID=100;
emp.Age=25;

I don't assign/get return value for name from GetEmpInfo() , will that throw any exception?

If you have a class with 10 properties and don't assign few, will it break the application?

Please share your thoughts. There is some code in production, i am not sure of the result, so am checking.

If your web service method returns null :

[WebMethod]
public Employee GetEmpInfo()
{
    return null;
}

then the following will throw a NullReferenceException :

emp.ID = 100;

because the emp variable won't be assigned.

In order to avoid this verify if the variable has been assigned before accessing its properties (or in your case public fields):

Employee emp = pp.GetEmpInfo(); 
if (emp != null)
{
    emp.ID = 100;
    emp.Age = 25;
}

After initial construction (before constructor is called), all fields are in initial (0 or null) state. For more complex value types, all of their fields are in initial (0 or null) state and so on, recursively.

It will not break the application, the attributes will have their default value - objects and strings will be set to null , booleans to false , integers/floats/doubles to 0 , chars to '\\0' etc.
You only might encounter null reference exceptions if you access object attributes that have not been set without checking them for null.

If GetEmpInfo() does not return a value, emp will still be null. Thus when you go to call a property (or in your case, a field) of emp , such as when you call emp.ID=100 , you will get a System.NullReferenceException (Object reference not set to an instance of an object). You might add a null check to your code:

Employee emp= pp.GetEmpInfo();  
//pp is an instance of webservices which is web referenced in the app. 

if (emp == null)
{
    //you might choose to throw an error or set it to a new
    //instance of an object.
    emp = new Employee();
}

emp.ID=100;
emp.Age=25; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM