I've got a base class from an outside library that I can't modify - here's the relevant piece:
public class BaseClass
{
List<string> _values;
public Values { get { return _values; } }
}
I am inheriting the BaseClass, and I want to set _values to a class that inherits from List(T) in the constructor:
public InheritingClass : BaseClass
{
public InheritingClass():base()
{
//set base._values = new InhertingList<string>(); ?
}
}
What's the best way to set base._values there? Is there a way to find what private variable is fetched by Values and set that in case the private variable is renamed in the future?
There are other ways I can accomplish what I need to do, but if I could do the following, it would be quicker by far than any ways of achieving my goal without setting the private property value.
Keeping it private, by definition, is meant to prevent this exact scenario.
The best option would be to implement a protected setter:
public class BaseClass
{
public Values {
get { return _values; }
protected set { _values = value; }
}
}
This way, your InheritingClass has access to the setter, and can do:
this.Values = new InhertingList<string>();
But since you can't change the base class, it is, technically, possible to do this via reflection (in a full trust scenario). I don't recommend this approach, though:
FieldInfo field = typeof(BaseClass).GetField("_value", BindingFlags.Instance | BindingFlags.NonPublic );
field.SetValue(this, this.Values = new InhertingList<string>() );
The danger of doing what you are attempting, btw, is that you're going to change the implementation defined by the BaseClass to something that you're providing. It's very easy to introduce subtle bugs, since you're (purposefully) "breaking" the implementation details in the base class.
I'd try to rethink your algorithm, and see if there's another way around this issue.
If you really need to set the value, you can use reflection. But that's no good coding style and may be slow.
Edit:
It might be possible to disassemble your BaseClass and change its implementation. Bun then you might have to disassemble the whole library.
Perhaps you can provide some more details on your problem?
Usually, when you don't have a property with an accessible setter provided for a field, it means that you should not modify that field from anywhere but the BaseClass - if the creator of the BaseClass class would have wanted you to be able to modify that field, he'd have exposed a property with a protected setter or something like that. So generally it's not recommended to hack it.
You could certainly do it by reflection though, providing you know the name of the private field - I don't think it is possible to extract the body of the property.
As for the other answers: he wrote "I've got a base class from an outside library that I can't modify".
You can't set the private property. You will either have to inherit from another base class or create your own base class that provides the behaviour.
Of course, depending on the level of trust your application is running under, you may be able to set the private variable via reflection but that would really be a hack to get around what is actual a problem in the design.
No, there is no way to do what you're looking for. Private variables are meant to be private - namely, they can't be seen or altered by any code.
Normally, when fields don't have mutator methods, you'd use the constructor of the class to instantiate the object (and it's relevant fields).
BaseClass base = new BaseClass(List<string> yourList);
You could always utilize the "new" keyword, but the inherited method would be ignored if the class is cast back to its base object
public InheritingClass : BaseClass
{
public InheritingClass()
{
Values = new InhertingList<string>(); ?
}
public new List<string> Values { get; private set; }
}
To access private fields you can use Reflection, but since the field is private I'm not certain how the inheriting class would benefit from changing a private field type.
public InheritingClass : BaseClass
{
private static FieldInfo _valueField = typeof(BaseClass).GetField("_values", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
public InheritingClass()
{
_valueField.SetValue(this, new InhertingList<string>());
}
}
http://msdn.microsoft.com/en-us/library/6z33zd7h(v=vs.110).aspx
Related
I have a similar problem to this user, however I've found that using generics introduces unnecessary verbosity in actual use.
(In my case, "MySpecificClass" uses one specific ICustom Values type, so T would always be just one type.)
My current "solution" is to define a backing member in the base class, and then define "new" properties that cast to the more specific type in the derived classes as such.
public class BaseMember { }
public class BaseOwner
{
protected BaseMember _member;
public BaseMember member {get => _member; private set => _member = value;}
}
public class DerivedMember: BaseMember { }
public class DerivedOwner : BaseOwner
{
public new DerivedMember member {get => (DerivedMember) _member; private set => _member = value;}
}
This feels very clever, and so far has not caused any issues. It also produces the exact interaction I'm looking for in terms of writing the higher level code that derives these classes.
It also looks like a huge time bomb, though I can't put my finger on it. What am I missing?
C# 9.0 allows to change the return type, use a more specific class. So you don't need new. See Covariant returns.
To use that you need to declare it as virtual in the base class and then override in the child.
Suppose you have the following A class definition:
class A
{
protected double[] _temperatures;
double[] Temperature
{
get {return _temperatures;}
set {_temperatures = value;}
}
}
How should I access temperatures in a derived class B? Using the member field or the property? Should I declare _temperatures as private and always use the property? What is the overhead of using the property instead of direct member field access?
Thanks.
You should use the property and make the field private. But your code with a custom private field only make sense if you really need to add some custom logic in the getter or setter. So for your simple case, you can go with this:
class A
{
protected double[] Temperature { get; set; }
}
Yes change the data member to private. Using a Property instead of a Field (private member) is a better way of accessing it even if its from within the same class so that if you have some logic in the getter/setter you don't have to repeat it each time you set the value.
Even if you don't have logic its better to use property as you might need to add some logic in future. It will be a single point of entry for getting and setting the value.
And yes as Kevin suggested you can use auto-implemented property if you don't have custom logic.
You may modify your code like this:
class A
{
private double[] _temperatures;
public double[] Temperature
{
get { return _temperatures; }
set { _temperatures = value; }
}
}
class B : A
{
public B()
{
B b = new B();
Console.WriteLine(b.Temperature);
}
}
Local variable '_temperatures' should be private and property 'Temperature' should be either public or protected.
Ideally a class should not expose its members (in your case _temperatures) to the outside world. Members are meant to be used internally with in a class. If you want to expose a class member then use properties. Thats ideal way of designing a class.
The advantage of this type of class designing is tomorrow suppose there is a need to add some logic when assigning a value or retrieving a value from a class member then it can be easily accomodated with in a property without redesigning the interface.
So declare _temperatures as private and expose it to derived classes by declaring the property Temperature as protected.
Refer this C# tutorial for additonal information:
Well my question is pretty self-explanatory. I have a class and I want to ensure that there is just 1 public constructor to this class. Moreover, I also want to ensure that the constuctor should have just 1 parameter. My class will be modified by many different developers, and I am looking for a way to ensure that they do not write any more constructors than are currently specified. Is it possible? If yes, then how?
Note, my class inherits from another class which currently does not have any constructor but it might have in the future. I don't know if this information will affect the answer or not but just thought of adding it.
Please help!
Thanks in advance!
You could consider writing a unit test to encode this design constraint. As long as the test isn't fiddled with, this will warn when the contraint is broken.
This would be a good case for a nice comment in your class detailing this constraint.
The following testing approach can be expanded to provide a test which could test derived types, rather than a single type. This approach is a type of static analysis, and removes the overhead that would be incurred by expensive runtime checking through reflection for instance. A test ensures that the design constraint is validated at build time, rather than at runtime which could be after code is released.
[Test]
public void myClass_must_have_one_single_paramter_ctor()
{
Type type = typeof(MyClass);
const BindingFlags Flags = (BindingFlags.Public | BindingFlags.Instance);
ConstructorInfo[] ctors = type.GetConstructors(Flags);
Assert.AreEqual(1, ctors.Length, "Ctor count.");
ParameterInfo[] args = ctors[0].GetParameters();
Assert.AreEqual(1, args.Length, "Ctor parameter count.");
Assert.AreEqual(typeof(string), args[0].ParameterType, "Ctor parameter type.");
}
public class MyClass
{
public MyClass(string woo) {}
}
All classes have one constructor. If you don't specify one in the source code, the compiler will add an empty public constructor - the equivalent of:
public class MyClass
{
public MyClass()
{
}
}
However if you specify at least one constructor in the source, only the constructors that you explicitly specify will be created, e.g. the following class has one public constructor that takes a single string parameter:
public class MyClass
{
public MyClass(string myParameter)
{
...
}
}
In short, there's nothing special you need to do. If you only want one public constructor then ... just write one public constructor.
Only the person who codes the class can restrict the number and type of constructors.
So if that is you, then you can just code it the way you want.
This could be achieved using reflection. The only thing you need to take care is, the base class code shouldn't be accessible to or editable by developers.
class Program
{
static void Main(string[] args)
{
Inherited obj = new Inherited("Alpha");
obj.test();
Inherited1 obj1 = new Inherited1(); //This will fail as there is no ctor with single param.
obj1.test();
}
}
public class MyBase
{
private static IList<string> ValidatedClasses = new List<string>();
public MyBase()
{
if(!ValidatedClasses.Contains(this.GetType().FullName) &&
!ValidateConstructorLogic())
{
throw new ApplicationException("Expected consturctor with single argument");
}
}
public bool ValidateConstructorLogic()
{
bool ValidConstFound = false;
foreach (var info in this.GetType().GetConstructors())
{
if(info.GetParameters().Length ==1)
{
lock (ValidatedClasses)
{
ValidatedClasses.Add(this.GetType().FullName);
}
ValidConstFound = true;
}
}
return ValidConstFound;
}
}
public class Inherited:MyBase
{
public Inherited(string test)
{
Console.WriteLine("Ctor");
}
public void test()
{
Console.WriteLine("TEST called");
}
}
public class Inherited1 : MyBase
{
public void test()
{
Console.WriteLine("TEST called");
}
}
You could use FxCop to validate your code against a set of predefined rules. I beleive this might be the apt solution to your problem. If you need help on creating custom FxCop rules, please refer this article.
Constructors are not inherited from base classes.
Your class will have only the constructors that you write, except for (as others have pointed out) a default public constructor that is generated by the compiler when you do not explicitly provide one of your own.
You could try using a nested builder, as described by Jon Skeet. Basically: You force the user to go through the builder which then calls the private class constructor. Since the class constructor is private, only the nested builder has access to it.
Alternative: Use static factory methods, make the constructor private & document your intentions.
Based on your comments, I don't think this is a "coding" problem. This is a policy & enforcement problem. You don't want other developers in your team creating more constructors.
In that case, go tell them that. Whoever is in charge of your source code repository can enforce it by rejecting changes that break the policy. Adding code to deal with this is just going to add runtime penalties to users for no reason.
I'm trying to create a class (in C#) that serves as an environment for my application.
I'm trying to make the class dynamic, and send it as a parameter to entities in my application. The problem is, that I want to be able to change the properties of this environment class (public setters), but at the same time I want the classes that receive the environment to be unable to use these setters.
I can't seem to find a good way to phrase my question (which I figure is a part of the reason I can't find anything like this on Google or msdn), but to put shortly, I want to create a class with setters that are public only for some of my objects and not for all.
I'm currently amusing the following idea:
Avoiding the public setters all together, and expose the private fields using event registration.
The class will register to events in a new third object (sent as a parameter to the constructor). The methods that will be registered by the environment are not much more then setters, and so triggering these events will "allow access" to the private fields.
I'd love some ideas (seeing as I feel that mine isn't all that great), or better yet some patterns I could make use of.
Thanks in advance
Isn't "internal" sufficient for what you need?
And you could move the setters into an interface as explicit implementation. Then they are hidden from the public interface and only accessible if you cast to the interface.
And if you want to make really sure that nobody else can call it you can add some parameter to these functions where you expect a certain token object which you only give to trusted classes.
void SetX(int value, object token)
{
if(token!=correctToken)
throw new ArgumentException("wrong token");
x=value;
}
You could create a proxy, and send that proxy to your entity classes.
class MyClass
{
public int MyProperty { get; set; }
}
class MyProxyClass
{
public MyProxyClass(MyClass myClass)
{
_myClass = myClass;
}
private MyClass _myClass;
public int MyProperty
{
get { return _myClass.MyProperty; }
}
}
You could try using Friend assemblies. That will allow only the assemblies you specify to have access to your privates (snicker).
Maybe i understood something not quite well, but i think Jon had a quite similar problem which he described here. Maybe this can help you.
How about
class Callee
{
public void SetX(TypeOfCaller caller, int value)
{
}
}
class TypeOfCaller
{
public void Do()
{
Callee instance;
//..
instance.SetX(this, 5);
}
}
Doing so; you can also use Visual Studio' Find References feature! In case you want multiple types of caller; you can either opt for class hierarchy or can simply have required overloads
Why not return clones of your protected objects instead of the actual objects? Solves the problem without adding any more complexity.
public class MyService
{
private List<MyObject> _protectedObjects = new List<MyObject>();
public MyObject GetItem(int id)
{
return (MyObject)_protectedObjects.First(i => i.Id == id).Clone();
}
}
public class MyObject : ICloneable
{
//[...]
public object Clone()
{
return MemberwiseClone();
}
}
As far as I know, in C#, there is no support for the "friend" key word as in C++. Is there an alternative way to design a class that could achieve this same end result without resorting to the un-available "friend" key-word?
For those who don't already know, the Friend key word allows the programmer to specify that a member of class "X" can be accessed and used only by class "Y". But to any other class the member appears private so they cannot be accessed. Class "Y" does not have to inherit from class "X".
No, there is no way to do that in C#.
One common workaround is to based the object for which you want to hide the constructor on an interface. You can then use the other object to construct a private, nested class implementing that interface, and return it via a Factory. This prevents the outside world from constructing your object directly, since they only ever see and interact with the interface.
public interface IMyObject
{
void DoSomething();
}
public class MyFriendClass
{
IMyObject GetObject() { return new MyObject(); }
class MyObject : IMyObject
{
public void DoSomething() { // ... Do something here
}
}
}
This is how I solved it. I'm not sure if it's the "right" way to do it, but it required minimal effort:
public abstract class X
{
// "friend" member
protected X()
{
}
// a bunch of stuff that I didn't feel like shadowing in an interface
}
public class Y
{
private X _x;
public Y()
{
_x = new ConstructibleX();
}
public X GetX()
{
return _x;
}
private class ConstructibleX : X
{
public ConstructibleX()
: base()
{}
}
}
No. The closest you have is an internal constructor, or a private constructor and a separate factory method (probably internal, so you haven't saved much).
What about just having it explicity implement an interface that is only visible to a certain class?
Something like:
public void IFreindOfX.Foo() //This is a method in the class that's a 'friend' to class X.
{
/* Do Stuff */
}
and then make sure IFriendOfX is visible to class X. In your X class you'd call the method by first casting X to IFriendOfX then calling Foo(). Another advantage is that is is fairly self documenting... that is, it's pretty close to having the friend keyword itself.
What about creating a private class? This does exactly what you seem to be describing. A member of class X can be accessed and used only by class Y, and to any other class it appears private, since, well, it is private:
public class Y
{
private class X { }
private X Friend;
public Y()
{
Friend = new X();
}
}
As far as I know, the Internal keyword is the closest thing in .NET. This question will shed more light on Internal: Internal in C#
The only thing I can think of that would even come close would be protected internal but that does not restrict it to a specific class. The only friending I'm aware of in c# is to make a friend assembly. Still does not restrict to a specific class.
The only thing I could think of to try and do it would be to do something like the following:
public class A
{
public A() {}
protected internal A(B b) {}
}
public class B
{
A myVersion;
public B()
{
myVersion = A(this);
}
}
The only other way I could think of would be to do some sort of Constructor Injection using reflection that is done inside of your friend class. The injection mechanism would allow you to limit it to what you want but could be very cumbersome. Take a look at something like Spring.Net for some injection capabilities.
As a workaround, I suppose you could create a conditional in your constructor that uses reflection.
For example, if Class1's constructor must be called by Class2:
public Class1()
{
string callingClass = new StackFrame(1).GetMethod().DeclaringType.Name;
if (callingClass != "Class2")
{
throw new ApplicationException(
string.Concat("Class1 constructor can not be called by ",
callingClass, "."));
}
}
EDIT:
Please note that I would never actually do this in "real" code. Technically it works, but it's pretty nasty. I just thought it was creative. :)
You can access private members/methods using Reflection.
Since it's got the design tag, I never particularly liked the friend keyword. It pierces encapsulation and that always felt dirty to me.
This has a bit of a smell. There are other plenty of other ways to achieve implementation hiding in C#. Limiting construction to only specific classes does not achieve all that much.
Could you please provide more information as to the purpose of this requirement? As already answered, internal is the closest match for limiting accessibility to the class. There are ways to build on top of that depending on the purpose.