Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As I learn that interface is also used for encapsulate method but in the following code by casting ojb to MainClass I am able to access other method from Mainclass which I did not declare in interface so now where is encapsulation occur.
C#
class Program
{
    static void Main(string[] args)
    {
        IInterface obj = new MainClass();
        Console.WriteLine(((MainClass)obj).FullName()+" " +obj.LastName());
        Console.WriteLine(((MainClass)obj).SayHello());
        Console.ReadKey();
    }
}

public interface IInterface
{
    string LastName();
}

public class MainClass:IInterface
{
    public  string FullName()
    {
        return "Raman Singh";
    }
    public string SayHello()
    {
        return "Hello Sir111";
    }

    public string LastName()
    {
        return "Chauhan";
    }
}
Posted
Updated 19-Jun-14 22:54pm
v2
Comments
phil.o 20-Jun-14 4:57am    
All of this has nothing to do with encapsulation. What makes you think it does?

1 solution

I just answered a very similar question to this - and that was yours as well.

Don't repost - it wastes time and annoys people.

But - there is a difference here, in that you are declaring your variable obj as a IInterface Type, which means it can contains an instance of any class with implements IInterface, and casting the variable to a specific derived class type - which means that (if the cast is successful) it will be a MainClass instance and you can then use all MainClass fields, properties, and methods.

If it isn't a MainClass instance, but a different class that implements IInstance then you will get a runtime error from the cast - but the system cannot definitely know that until your application runs.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900