To access Protected Field of Parent class in child class - c#-4.0

I am trying to access protected member variables in different ways in the child class. I found I can not do so by using object reference of child class to parent class object. Here I am referring to "int Number6" in the following program.
However I can access "int Number7" which is public. I want to know the reason behind this.
public class Customer
{
#region Fields
protected int Number2;
protected int Number3;
protected int Number4;
protected int Number5;
protected int Number6;
public int Number7;
#endregion
}
public class CorporateCustomer : Customer
{
public void PrintID()
{
CorporateCustomer CC = new CorporateCustomer();
CC.Number2 = 101;
base.Number3 = 103;
this.Number4 = 104;
Customer C2 = new CorporateCustomer();
C2.Number6 = 106; //-> Not Possible to access protected Number6 by this way
C2.Number7 = 105; //-> However, can access public field
}
}

Interesting question - the msdn states that this won't work:
A protected member of a base class is accessible in a derived class
only if the access occurs through the derived class type.
Since you are using the basetype instead of the derived type, consequently this does not work.
But why? I could imagine that this relates to the issue that a Customer could also be derived by another class than CorporateCustomer. In this case the instance that you assigned to Customer would not necessarily be a CorporateCustomer and so the protected attribute correctly forbids to access the Number6 property because it would break the accessibility restriction.
public class PrivateCustomer : Customer
{
}
public class CorporateCustomer : Customer
{
public void PrintID()
{
Customer C = new PrivateCustomer();
C.Number6 = 106; //-> Not Possible to access protected Number6 by this way which is alright, as this is not a Corporate Customer
C.Number7 = 105; //-> However, can access public field
}
}
The C# Language Specification states exactly this example as a reason this doesn't work:
3.5.3 Protected access for instance members When a protected instance member is accessed outside the program text of the class in which it
is declared, and when a protected internal instance member is accessed
outside the program text of the program in which it is declared, the
access must take place within a class declaration that derives from
the class in which it is declared. Furthermore, the access is required
to take place through an instance of that derived class type or a
class type constructed from it. This restriction prevents one derived
class from accessing protected members of other derived classes, even
when the members are inherited from the same base class.

Related

Make property in parent object visible to any of its contained objects

I have a class CalculationManager which is instantiated by a BackgroundWorker and as such has a CancellationRequested property.
This CalculationManager has an Execute() method which instantiates some different Calculation private classes with their own Execute() methods which by their turn might or might not instantiate some SubCalculation private classes, in sort of a "work breakdown structure" fashion where each subclass implements a part of a sequential calculation.
What I need to do is to make every of these classes to check, inside the loops of their Execute() methods (which are different from one another) if some "global" CancellationRequested has been set to true. I put "global" in quotes because this property would be in the scope of the topmost CalculationManager class.
So, question is:
How can I make a property in a class visible to every (possibly nested) of its children?
or put down another way:
How can I make a class check for a property in the "root object" of its parent hierarchy? (well, not quite, since CalculationManager will also have a parent, but you got the general idea.
I would like to use some sort of AttachedProperty, but these classes are domain objects inside a class library, having nothing to do with WPF or XAML and such.
Something like this ?
public interface IInjectable {
ICancelStatus Status { get; }
}
public interface ICancelStatus {
bool CancellationRequested { get; }
}
public class CalculationManager {
private IInjectable _injectable;
private SubCalculation _sub;
public CalculationManager(IInjectable injectable) {
_injectable = injectable;
_sub = new SubCalculation(injectable);
}
public void Execute() {}
}
public class SubCalculation {
private IInjectable _injectable;
public SubCalculation(IInjectable injectable) {
_injectable = injectable;
}
}
private class CancelStatus : ICancelStatus {
public bool CancellationRequested { get; set;}
}
var status = new CancelStatus();
var manager = new CalculationManager(status);
manager.Execute();
// once you set status.CancellationRequested it will be immediatly visible to all
// classes into which you've injected the IInjectable instance

initializing derived class member variables using base class reference object

I came across a lot of code in our company codebase with the following structure
class Base
{
public Base (var a, var b)
{
base_a = a;
base_b = b;
}
var base_a;
var base_b;
}
class Derived:Base
{
publc Derived (var a,b,c,d): base (a,d)
{
der_c = c;
der_d = d;
}
var der_c;
var der_d;
var der_e;
}
class Ref
{
Base _ref;
public Ref( var a,b,c,d)
{
_ref = new Derived (a,b,c,d)
}
public void method( )
{
_ref.der_e = 444; // won't compile
}
}
What is the correct way to initialize der_e ? What is the advantages of having a reference of base class and using an object derived class for _ref ? Just the fact that using a base class reference can hold multiple derived class objects ? If that's the case, should all the member variables of derived class be initialized during construction itself (like this: _ref = new Derived (a,b,c,d) ). What if I want to initialize _ref.der_e later in a method ? I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e = 444) but this look doesn't seem to the best practice. What is the idea of having such a structure and what is the correct of initializing a member of a derived class object after it has been constructed ?
Those are too many questions in a single post.
What is the correct way to initialize der_e ?
For initializing der_e you will have to have Reference of Derived class as it knows about the der_e property and not Base class.
What is the advantages of having a reference of base class and using
an object derived class for _ref ?
Yes that's called Polymorphism which is the essence of Object Oriented Programming. It allows us to hold various concrete implementations without knowing about the actual implementation.
If that's the case, should all the member variables of derived class
be initialized during construction itself (like this: _ref = new
Derived (a,b,c,d) )
There is no such rule. It depends on your scenario. If the values are not meant to be changed after the creation of the object and the values are known before hand during construction of the object then they should be initialized during construction.
Again if there are various scenarios like sometimes values are known and sometimes not then there can be Overloaded Constructors, which take different arguments.
What if I want to initialize _ref.der_e later in a method ?
That is perfectly fine, it depends on what you are trying to achieve. The question is not a concrete one but an abstract one in which it is difficult to comment on what you are trying to achieve.
I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e =
444) but this look doesn't seem to the best practice.
I am sharing some Java code which is similar to C# as I am from Java background
//This class knows about Base and nothing about the Derived class
class UserOfBase{
Base ref;
//Constructor of UserOfBase gets passed an instance of Base
public UserOfBase(Base bInstance){
this.ref = bInstance;
}
//Now this class should not cast it into Derived class as that would not be a polymorphic behavior. In that case you have got your design wrong.
public void someMethod(){
Derived derivedRef = (Derived)ref; //This should not happen here
}
}
I am sharing some references which would help you with this, as I think the answer can be very long to explain.
Factory Pattern
Dependency Injection
Head First Design Patterns
Posts on SO regarding polymorphism
You can create a constructor in your derived class and map the objects or create an extension method like this:
public static class Extensions
{
public static void FillPropertiesFromBaseClass<T1, T2>(this T2 drivedClass, T1 baseClass) where T2 : T1
{
//Get the list of properties available in base class
System.Reflection.PropertyInfo[] properties = typeof(T1).GetProperties();
properties.ToList().ForEach(property =>
{
//Check whether that property is present in derived class
System.Reflection.PropertyInfo isPresent = drivedClass.GetType().GetProperty(property.Name);
if (isPresent != null && property.CanWrite)
{
//If present get the value and map it
object value = baseClass.GetType().GetProperty(property.Name).GetValue(baseClass, null);
drivedClass.GetType().GetProperty(property.Name).SetValue(drivedClass, value, null);
}
});
}
}
for example when you have to class like this:
public class Fruit {
public float Sugar { get; set; }
public int Size { get; set; }
}
public class Apple : Fruit {
public int NumberOfWorms { get; set; }
}
you can initialize derived class by this code:
//constructor
public Apple(Fruit fruit)
{
this.FillPropertiesFromBaseClass(fruit);
}

groovy: variable scope in closures in the super class (MissingPropertyException)

I have the impression that closures run as the actual class being called (instead of the implementing super class) and thus break when some variables are not visible (e.g. private in the super class).
For example
package comp.ds.GenericTest2
import groovy.transform.CompileStatic
#CompileStatic
class ClosureScopeC {
private List<String> list = new ArrayList<String>()
private int accessThisPrivateVariable = 0;
void add(String a) {
list.add(a)
println("before ${accessThisPrivateVariable} ${this.class.name}")
// do something with a closure
list.each {String it ->
if (it == a) {
// accessThisPrivateVariable belongs to ClosureScopeC
accessThisPrivateVariable++
}
}
println("after ${accessThisPrivateVariable}")
}
}
// this works fine
a = new ClosureScopeC()
a.add("abc")
a.add("abc")
// child class
class ClosureScopeD extends ClosureScopeC {
void doSomething(String obj) {
this.add(obj)
}
}
b = new ClosureScopeD()
// THIS THROWS groovy.lang.MissingPropertyException: No such property: accessThisPrivateVariable for class: comp.ds.GenericTest2.ClosureScopeD
b.doSomething("abc")
The last line throws a MissingPropertyException: the child class calls the "add" method of the super class, which executes the "each" closure, which uses the "accessThisPrivateVariable".
I am new to groovy, so I think there must be an easy way to do this, because otherwise it seems that closures completely break the encapsulation of the private implementation done in the super class ... this seems to be a very common need (super class implementation referencing its own private variables)
I am using groovy 2.1.3
I found this to be a good reference describing how Groovy variable scopes work and applies to your situation: Closure in groovy cannot use private field when called from extending class
From the above link, I realized that since you have declared accessThisPrivateVariable as private, Groovy would not auto-generate a getter/setter for the variable. Remember, even in Java, private variables are not accessible directly by sub-classes.
Changing your code to explicitly add the getter/setters, solved the issue:
package com.test
import groovy.transform.CompileStatic
#CompileStatic
class ClosureScopeC {
private List<String> list = new ArrayList<String>()
private int accessThisPrivateVariable = 0;
int getAccessThisPrivateVariable() { accessThisPrivateVariable }
void setAccessThisPrivateVariable(int value ){this.accessThisPrivateVariable = value}
void add(String a) {
list.add(a)
println("before ${accessThisPrivateVariable} ${this.class.name}")
// do something with a closure
list.each {String it ->
if (it == a) {
// accessThisPrivateVariable belongs to ClosureScopeC
accessThisPrivateVariable++
}
}
println("after ${accessThisPrivateVariable}")
}
}
// this works fine
a = new ClosureScopeC()
a.add("abc")
a.add("abc")
// child class
class ClosureScopeD extends ClosureScopeC {
void doSomething(String obj) {
super.add(obj)
}
}
b = new ClosureScopeD()
b.doSomething("abc")
There is a simpler way, just make the access modifier (should rename the property really) to protected, so the sub-class has access to the property.. problem solved.
protected int accessThisProtectedVariable
To clarify on your statement of concern that Groovy possibly has broken encapsulation: rest assured it hasn't.
By declaring a field as private, Groovy is preserving encapsulation by intentionally suspending automatic generation of the public getter/setter. Once private, you are now responsible and in full control of how or if there is a way for sub-classes (protected) or all classes of objects (public) to gain access to the field by explicitly adding methods - if that makes sense.
Remember that by convention, Groovy ALWAYS calls a getter or setter when your codes references the field. So, a statement like:
def f = obj.someField
will actually invoke the obj.getSomeField() method.
Likewise:
obj.someField = 5
will invoke the obj.setSomeField(5) method.

claimsprincipalpermission is not verified for parent class if child class has already attribute

I have a base base and derived classes like
[ClaimsPrincipalPermission(SecurityAction.Demand, Resource = "Base",
Operation = "Create")]
public abstract class Base
{
}
[ClaimsPrincipalPermission(SecurityAction.Demand, Resource = "Derived",
Operation = "Create")]
public class Derived : Base
{
}
It never comes to authorization manager to check for base class if I am creating a derived class object.
public class AuthorisationManager : ClaimsAuthorizationManager
{
public override bool CheckAccess(AuthorizationContext context)
{
var resource = context.Resource.First().Value;
var action = context.Action.First().Value;
return context.Principal.HasClaim(resource, action);
}
}
Any idea how can I implement that it should come to check for derived and base class both? Actually I want that if any one of them has permission, object should be allowed to create.
Is that your real scenario? Or do you want to use that in the context of some app framework like ASP.NET?
But IIRC this is the behavior of CAS permissions - you could try the same with good old PrincipalPermission to see if the behavior wrt derivation is the same.

Does not contain a constructor that takes 0 arguments

I get an error stating "Products does not contain a constructor that takes 0 arguments" from the following code:
public class Products
{
string id;
string name;
double price;
int soldCount;
int stockCount;
public Products(string id, string name, double price,
int soldCount, int stockCount, double tax)
{
this.id = id;
this.name = name;
this.price = price;
this.soldCount = soldCount;
this.stockCount = stockCount;
}
}
//I have got some get and set values for the code above
//but it would have been too long to put in here
public class FoodProducts : Products
{
public FoodProduct()
{
Console.WriteLine("This is food product");
}
public void Limit()
{
Console.WriteLine("This is an Attribute of a Product");
}
}
Several rules about C# come into play here:
Each class must have a constructor (In order to be, well constructed)
If you do not provide a constructor, a constructor will be provided for you, free of change, automatically by the compiler.
This means that the class
class Demo{}
upon compilation is provided with an empty constructor, becoming
class Demo{
public Demo(){}
}
and I can do
Demo instance = new Demo();
If you do provide a constructor (any constructor with any signature), the empty constructor will not be generated
class Demo{
public Demo(int parameter){}
}
Demo instance = new Demo(); //this code now fails
Demo instance = new Demo(3); //this code now succeeds
This can seem a bit counter-intuitive, because adding code seems to break existing unrelated code, but it's a design decision of the C# team, and we have to live with it.
When you call a constructor of a derived class, if you do not specify a base class constructor to be called, the compiler calls the empty base class constructor, so
class Derived:Base {
public Derived(){}
}
becomes
class Derived:Base {
public Derived() : base() {}
}
So, in order to construct your derived class, you must have a parameterless constructor on the base class. Seeing how you added a constructor to the Products, and the compiler did not generate the default constructor, you need to explicitly add it in your code, like:
public Products()
{
}
or explicitly call it from the derived constructor
public FoodProduct()
: base(string.Empty, string.Empty, 0, 0, 0, 0)
{
}
Since Products has no constructor that takes 0 arguments, you must create a constructor for FoodProducts that calls the constructor of Products will all the required arguments.
In C#, this is done like the following:
public class FoodProducts : Products
{
public FoodProducts(string id, string name, double price, int soldCount, int stockCount, double tax)
: base(id, name, price, soldCount, stockCount, tax)
{
}
public void Limit()
{
Console.WriteLine("This is an Attribute of a Product");
}
}
If you don't want to add this constructor to FoodProducts, you can also create a constructor with no parameter to Products.
the constructor of the inherited class needs to construct the base class first. since the base class does not have a default constructor (taking 0 arguments) and you are not using the non-default constructor you have now, this won't work. so either A) add a default constructor to your base class, in which case the code of the descending class needs no change; or B) call the non-default constructor of the base class from the constructor of the descending class, in which case the base class needs no change.
A
public class Products
{
public Products() { }
}
public class FoodProducts : Products
{
public FoodProducts() { }
}
B
public class Products
{
public class Products(args) { }
}
public class FoodProducts : Products
{
public FoodProducts(args) : base(args) { }
}
some of this is explained rather OK on msdn here.
As you inherit from Products, you must call a base construct of Products in your own class.
You didn't write:base(id, name, ....) so C# assumes you call the default parameterless constructor, but it doesn't exist.
Create a default parameterless constructor for Products.
Just add
public Products()
{
}
in your products class And you will not get error
Reason:
There exists a default constructor with 0 parameter for every class. So no need to define/write it explicitly (by programmer) BUT when you overload a default constructor with your desired number and type of parameters then it becomes a compulsion to define the default constructor yourself (explicitly) along with your overloaded constructor

Resources