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.
Place both classes in a separate assembly and make the method internal.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With