Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to restrict access to a public method to only a specific class in C#?

Tags:

c#

oop

I have a class A with a public method in C#. I want to allow access to this method to only class B. Is this possible?

UPDATE:

This is what i'd like to do:

public class Category
{
    public int NumberOfInactiveProducts {get;}
    public IList<Product> Products {get;set;}

    public void ProcessInactiveProduct()
    {
        // do things...

        NumberOfInactiveProducts++;
    }
}

public class Product
{
    public bool Inactive {get;}
    public Category Category {get;set;}

    public void SetInactive()
    {
        this.Inactive= true;
        Category.ProcessInactiveProduct();
    }
}

I'd like other programmers to do:

var prod = Repository.Get<Product>(id);
prod.SetInactive();

I'd like to make sure they don't call ProcessInactiveProduct manually:

var prod = Repository.Get<Product>(id);
prod.SetInactive();
prod.Category.ProcessInactiveProduct();

I want to allow access of Category.ProcessInactiveProduct to only class Product. Other classes shouldn't be able to call Category.ProcessInactiveProduct.

like image 585
Anon Avatar asked Apr 13 '10 13:04

Anon


3 Answers

Place both classes in a separate assembly and make the method internal.

like image 170
Henrik Avatar answered Oct 23 '22 15:10

Henrik


You can if you make class A a private, nested class inside class B:

class B
{
    class A
    {
        public Int32 Foo { get; set; }
    }
}

Only B will be able to see A and it's members in this example.

Alternatively you could nest B inside A:

class A
{
    Int32 Foo { get; set; }

    public class B { }
}

In this case everyone can see both A and B but only B can see A.Foo.

like image 22
Andrew Hare Avatar answered Oct 23 '22 16:10

Andrew Hare


You can restrict method/class access in this way:

[StrongNameIdentityPermissionAttribute(SecurityAction.Demand, PublicKey="…hex…", Name="App1", Version="0.0.0.0")]
public class Class1 { } 

Take a look here http://msdn.microsoft.com/en-us/library/c09d4x9t.aspx for more info.

Managed code offers several ways to restrict method access:
...

  • Limit the method access to callers of a specified identity--essentially, any particular evidence (strong name, publisher, zone, and so on) you choose.
like image 2
theb1uro Avatar answered Oct 23 '22 16:10

theb1uro