Lorago
Lorago

Reputation: 161

How to disable type casting from interface to class that implements interface

How do I disable casting from interface IFoo to class Bar? Is it even possible?

Assembly one

public interface IFoo
{
   string Name { get; }
}

public class Foo : IFoo
{
   public int SecretValue { get; private set; }
   public string Name     { get; private set; }
}

Assembly two

public class Bar : Foo
{
   private IFoo secretFoo;
}

Can I prevent Bar from casting secretFoo to type Bar and thus accessing the value of SecretValue?

Upvotes: 0

Views: 150

Answers (1)

windfog
windfog

Reputation: 209

Change Bar's base class from Foo to IFoo, and property secretFoo from type IFoo to Foo.

public class Bar : IFoo
{
    private Foo secretFoo;
    public string Name {
        get
        {
            return secretFoo.Name;
        }
    }
}

Upvotes: 1

Related Questions