I have a abstract class ...
public abstract class MyClass
{
// other properties
public bool IsTypeDefault {get;set;}
}
I have a number of other classes that inherit from MyClass, say, MyClassA, MyClassB, MyClassC, etc.
And I have a collection class defined as ...
public class MyCollection : List<MyClass>
{
public SetAsTypeDefault(MyClass item)
{
}
}
The method SetAsTypeDefault should take an object of type MyClass, it will search the collection for a items of the same specific type, unset the IsTypeDefault on any item it finds where that value is true and then set it as true for the item that matches the passed in parameter.
What I want is to stop someone from setting the IsTypeDefault value on an individual instance of the collection directly and I can't figure out how to do it.
I can make IsTypeDefault readonly, but then I can't set it from the collection class. I can set it as private set and have a method set it, but the method needs to be public to be callable from the collection.
I'm only going to the bother of trying to do this 'cos the devs accessing this class are going to be completely out of my control. Nor am I going to be able to review their code and I want to make sure that they don't mess things up.
I appreciate that there I can't stop them from deliberately breaking stuff, for example, using reflection, but if they do this I want it to be because they are doing it on purpose rather than just being careless.
Is it possible?
A post-Post thought
I suppose I could attach an event to the IsTypeDefault property and have the collection class subscribe to the event, have it (the collection) do the verification before allowing (or not) the change to the instance in the collection. Yes?
If both MyCollection and MyClass are within the same assembly, but the developers using it are not - then its a simple case of making the setter internal
public abstract class MyClass
{
// other properties
public bool IsTypeDefault {get; internal set;}
}
Related
public class A
{
public int i;
public string s;
}
public class B
{
public int bi;
public A A;
}
Here I get the properties of class B which in turn returns both the properties available.
However I need to differentiate the normal class properties to the complex properties.
I need to handle the property A of class B differently. Can somebody advise how I can write code to decide that this property is of type of another class?
I just gave an example of Class A as child in Class B here. In real-time, there can be many children.
I'm going to assume that by "normal class properties" and "complex properties" you mean value and reference types, as that's what your example seems to imply.
If this is the case, you can use Type.IsValueType to check whether the type of each field or property is a value type. If it isn't a value type, that means it is a reference to another class, and you can act accordingly.
In the following code
// MVVM Views part class
public partial class DashBoard : UserControl
{
public DashBoard()
{
InitializeComponent();
this.DataContext = new DashBoardViewModel();
}
}
Could we use base.DataContext instead this.DataContext. In which case could we use base instead of this?
It's usually clearer to use this. You normally only specify base when you want to explicitly call a base class constructor or the base implementation of an overridden method or property.
Using base.DataContext would work, but it would might imply that this.DataContext would mean something different.
You use this to access a method defined in the present class (or superclass if it's not in the present class). You use base to access a method in the superclass or higher. In this case you could have used either (or none as Marc points out above).
I prefer to emit this except when it's (rarely) required.
To add to what the others have said, base. is used when you've overridden something from the base class with either the overrides or new keywords, you'll need to use base to gain access to the original method.
class a
{
public virtual void method1()
{
}
public string property1 { get; set; }
}
class b : a
{
// this has it's own instance in b, the only way to get to
// the original property1 is with base (or reflection)
public new string property1 { get; set; }
public override void method1()
{
// the only way to get to the original method1 and property1
base.method1();
base.property1 = "string";
}
}
In your example if the DataContext property uses either of these keywords then base and this don't mean the same thing at all.
Considering your case u are trying to initialize DataContext property of class DashBoard with some value. So if you then call DataContext typed property of (base)UserControl class object, it still will be not initialized. Therefore, to decide which property to initialize, u must to look to your program's logic.
Basicly MSDN tells that u should use (base.) in two scenarious:
-Call a method on the base class that has been overridden by another method.
-Specify which base-class constructor should be called when creating instances of the derived class.
In my practise i used first scenario when (this) method ends with exception, i was trying to call more general (base) method. Good luck!
I have a class that instantiates two classes which implement interfaces. I want one class to notify another class that something is OK. I could do it with an Action and then use private variables in the class but wondered if there was a direct way of doing it with properties so that when a property's value changes it updates a property on another class.
For example:
public class MyClass
{
public ILogger Logger {get;set;}
public ILogic Logic {get;set;}
private Form MyWinform;
public void Setup()
{
MyWinform = new MyWinform();
MyWinform.StartBatch += Logger.CreateFile; //Create file when user presses start
//How can I set a property on ILogic to be AllOk once ILogger says so??
//I could use an Action so that once all is ok I call IDecidedAlOK in ILogger which
//can then assign a private bool variable inside the class
Logic.ItsOKMethodSoSetVariableToTrue = Logger.IDecidedAllOKMethod;
}
public void DataIn(string Value)
{
Logic.DataIn(Value);
}
public void CreateInstances()
{
Logger = new FileLogger();
Logic = new MyLogic();
}
}
public class MyLogic : ILogic
{
public void DataIn(string Value)
{
//I want to check that all is ok before I do anything
//if (!AllOK)
//return;
//Do stuff
}
}
Implement INotifyPropertyChanged interface and subscribe to PropertyChanged event
I feel like it might be a bit more conventional to have your ILogger interface expose something like a "FileCreated" or "Ready" event, and allow your application to handle that event in order to update the ILogic object (or do whatever else is necessary).
EDIT: my apologies, after re-reading the question, I think I misunderstood what you were asking for.
There isn't any "natural" object that does exactly what you're asking, but you could create an anonymous delegate (or lambda expression) for this purpose:
Action<bool> loggerResult = (value) => Logic.ItsOKMethodSoSetVariableToTrue = value;
A property internally consists of two private methods, a get_XXX and a set_XXX, so unless you want to fetch the MethodInfo of those methods and invoke them (which are again methods) you have no choice but to implement a method calling approach.
Subscribing to event (INotifyPropertyChanged or some custom one) is OK, so is the method to pass a lambda-setter, but in some cases it might be more convinient to use a shared context object (much like the shared memory concept):
class ConversationContext
{
public bool EverythingIsOK { get; set;}
}
This object is passed to all interested objects (ILogic and ILogger) and they operate directly on it, instead of some internal properties. If change notifications are required, Implement INotifyPropertyChanged on it.
One positive aspect of this approach is that you won't get tangled in repeatedly firing events triggering other events and so on. A single object will hold the current state and no recurrent updates are needed.
Again, this is just one of many options.
I see a lot of code uses automatically generated property like {get; private set;} or {get; protected set;}.
What's the advantage of this private or protected set?
I tried this code, but it's the same when I have Foo{get; set;}.
public class MyClass
{
public int Foo {get; private set;}
public static void RunSnippet()
{
var x = new MyClass();
x.Foo = 30;
Console.WriteLine(x.Foo);
}
...
}
It makes a property read-only by external sources (i.e. classes that aren't MyClass and/or its subclasses). Or if you declared the property protected with a private set, it's read-only by its subclasses but writable by itself.
It doesn't make a difference in your class because your setter is private to that class, so your class can still access it. However if you tried to instantiate MyClass from another class, you wouldn't be able to modify the Foo property's value if it had a private or protected setter.
private and protected mean the same here as they do elsewhere: private restricts access only to that very class, while protected restricts access to that class and all its derived classes.
It makes a difference when you have a class model that uses inheritance. If your MyClass methods are clients of your private fields and methods it makes no difference.
That said, even if you don't anticipate your MyClass becoming a parent class in any sort of class hierarchy, it doesn't hurt to limit your field and method scope to the least visible scope that it requires. Encapsulate what you can with the least visible scope by default so that you don't have to refactor when subclasses start to access parent properties that they shouldn't be. The level of effort isn't any different from not doing so.
If you specify no access modifiers on the get and set keywords, the property will be accessible according to the access modifier of the property itself. In your example, you would be able to get the value of Foo and set the value of Foo from anywhere in your program if you specify get instead of private get.
In order to write robust code, you should try to always choose the most restrictive access modifier possible. It is a good idea to use properties to expose the state of your object, but not to change the state of your object from outside. If you want to change the state of your object, use method calls instead.
Think of the get and set functions in terms of accessor and mutator methods (except that you don't have to explicitly write the method bodies out:
private int foo;
public int get_Foo()
{
return foo;
}
public /* or protected, or private */ void set_Foo(int value)
{
foo = value;
}
After you see it like that, know that the protected and private modifiers work the same on a setter as they do on any other sort of member.
I' ve been doing some programming lately and faced an issue which i found weird in c#. (at least for me)
public class Foo
{
//whatever
public class FooSpecificCollection : IList<Bar>
{
//implementation details
}
public FooSpecificCollection GetFoosStuff()
{
//return the collection
}
}
I want the consumer of Foo to be able to obtain a reference to FooSpecificCollection, even perform some operations on it. Maybe even set it to some other property of Foo or smth like that, but not To be able to CREATE an instance of this class. (the only class that should be able to instatiate this collection should be Foo.
Is my request really that far-fetched? I know that people way smarter defined c# but shouldn't there be such an option that a parent class can create a nested class instance but nobody else can't.
So far I created a solution to make an abstract class, or interface available through the property and implement a concrete private class that is not available anywhere else.
Is this a correct way to handle such a situation.?
The way embedded classes work is that they, as members of the outer class, get access to private members of that outer class. But not the other way around (what is what you want).
You can shield the constructor of FooSpecificCollection, but then the Factory has to be part of FooSpecificCollection itself. It could enlist the outer class:
public class Foo
{
public class FooSpecificCollection : List<Bar>
{
private FooSpecificCollection () { }
public static FooSpecificCollection GetFoosStuff()
{
var collection = new FooSpecificCollection ();
PrepareFooSpecificCollection(collection);
return collection;
}
}
private static void PrepareFooSpecificCollection(FooSpecificCollection collection)
{
//prepare the collection
}
}
Make your nested class private and make the return value of GetFoosStuff IList<Bar> instead of FooSpecificCollection.
Also, there's a good chance that deriving from List<Bar> is a bug.
If you are creating a library for others to use, you could make the constructor internal. Anyone outside the library will not be able to access it. If you are concerned about calling the constructor in your own project, just don't call it outside the parent class.
We create classes all the time which are not directly related to other classes, but the constructors don't have to be hidden from non-related classes. We (the programmers) know the the objects are not related so we don't ever create an instance of one in the other.
There is a solution but I don't think I would use it in my App :)
The idea is to have derived class from FooSpecific which is private and can be used only inside Foo but has public constructor, so Foo can create its instances.
public class Foo
{
//whatever
public class FooSpecific
{
// Protected contructor.
protected FooSpecific()
{
}
// All other code in here.
}
// Private helper class used for initialization.
private class FooSpecificInitHelper : FooSpecific
{
public FooSpecificInitHelper()
{
}
}
// Method in foo to create instaces of FooSpecific.
private FooSpecific CreateFooSpecific()
{
return new FooSpecificInitHelper();
}
}
No, and it doesn't really make sense.
I mean the whole point is so that you could potentially return other instances; but who will be deriving from that class anyway? Certainly not any other classes (Because that would be wrong, and imply it shouldn't be hidden inside the main class), so ...