gayanrathnayaka
gayanrathnayaka

Reputation: 41

Interface Object Always Null

I created "personFuntionality" object from "PersonFuntionality" interface. that Interface has a method to save details of a person.The Problem is personFuntionality always has a null value.

public PersonFuntionality personFuntionality;



 try
            {
                List<beans.Person> prsn = new List<beans.Person>();

                beans.Person psn = new beans.Person();

                psn.PersonId = Convert.ToInt32(txtId.Text.Trim());
                psn.PersonName = txtName.Text.Trim();
                psn.PersonCity = txtCity.Text.Trim();

                prsn.Add(psn);

                //prsn.PersonId = Convert.ToInt32(txtId.Text.Trim());
                //prsn.PersonName = txtName.Text.Trim();
                //prsn.PersonCity = txtCity.Text.Trim();

                if (personFuntionality != null)
                {
                    bool success = personFuntionality.SavePersonDetails(prsn);

                    if (success == true)
                    {
                        lblResult.Text = "success";
                    }
                    else
                    {
                        lblResult.Text = "Failed";
                    }
                }
                else
                {
                    lblResult.Text = "Object Null";
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

Upvotes: 0

Views: 12185

Answers (1)

Adil
Adil

Reputation: 148180

You never instantiated the personFuntionality object in give code but just declared it. You can instantiate it as under. I assume you have parameter less constructor for class PersonFuntionalityImlementorClass that implemented PersonFuntionality Interface.

public PersonFuntionality personFuntionality = new  PersonFuntionalityImlementorClass();

You have the interface reference personFuntionality. You have to assign a implementer class object to it.

Interface

An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition. In the following example, class ImplementationClass must implement a method named SampleMethod that has no parameters and returns void.

interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation:  
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

Upvotes: 5

Related Questions