In my projects, I often have many static Objects of a class (let's say class A).
I create an additional class B to store the static Objects of class A, because else it would be too messy to store all static Objects in their own class:
public class A{
public A(...){
...
}
}
public class B{
public static A a1 = new A(...);
public static A a2 = new A(...);
public static A a3 = new A(...);
...
}
Then I access these Objects with B.a1, B.a2, ...
Is there a better way to store a large number of Objects?
This is a bit too general to answer. Why exactly do you need these static instances?
If it's a small number of commonly used instances, it really makes the most sense for them to be within the class itself. Look at BigInteger, which has static instances for 0, 1, and 10 within the class.
Related
As I know, if the static method from other class, we may interpret their relationship with dependency, just like the answer from How to show usage of static methods UML Class Diagram
However, how about for the static variable from other class? Is it the similar case; using dependancy?
For example,
class A{
public static String CHAR="Charecter";
public static String INT="Integer";
public static String STR="String";
}
class B{
public String Type;
public B(){
Type=STR;
}
public void B(String t){
Type=t;
}
}
would it result in the uml class diagram as below?
Note that although I would rather use enumeration in real life for this case, I just would like to know how it works.
Yes, this is similar.
Dependency shows that one class is "aware" of some other class and uses it in some way (or more generally depends on it). It can for instance refer to (public) static attributes, static operations and so on.
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.
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);
}
I tried to understand how it works but i am very slow with this(( so i decided ti ask here. In my prohramm i have static public class with different variables arrays, tabControls, Sizes, Pens an so on. But i need to set and get values of the variables from different threads how could i do it?
i have a class
public static class GLOBAL_STATIC_DATA
{
//.....
private static Size _get_Active_Project_ViewPort_Size()
{
//.....
}
public static Size Active_Project_ViewPort_Size
{
get
{
return _get_Active_Project_ViewPort_Size();
}
}
public static int Get_Panorama_Original_Image_Width()
{
}
public static TabControl MainTab = new TabContol();
public static int someInt = 100;
}
I need to write and to read all of that from different threads, could somebody help how shoud i change this static class to be able do that.
You just precede the public static entries with the class name...for example:
Size sz = GLOBAL_STATIC_DATA.Active_Project_ViewPort_Size;
This question is pertaining to the usage of MEF.
I want to provide different values for the same import in these two scenarios
[Export("A1", typeof(IA))]
[Export("A2", typeof(IA))]
class A : IA
{
[Import("B")]
public IB B;
}
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(IA))]
class A : IA
{
[Import]
public IB B;
}
In both of the two scenarios above, I want to satisfy the import of IB with different values that is when I do this in the first type of export
var a1 = Container.GetExportedValue<IA>("A1");
var a2 = Container.GetExportedValue<IA>("A1");
or this in the second export
var a1 = Container.GetExportedValue<IA>();
var a2 = Container.GetExportedValue<IA>();
I want the two instance of A a1 and a2 to have different values of IB. I don't want to use ImportMany because then I have to decide which one to choose and I want to keep that logic out of class A.
The two scenarios related to these exports are that I want to have a common generic view to work with different types of view models implementing some interface and different instances of a class that provides some service to be configured with different configuration parameters.
Perhaps you are looking for something like this?
public class AExporter
{
[Export("A1", typeof(IA)]
public IA A1
{
get
{
return new A(this.B1);
}
}
[Export("A2", typeof(IA)]
public IA A2
{
get
{
return new A(this.B2);
}
}
[Import("B1", typeof(IB))]
public IB B1 { private get; set; }
[Import("B2", typeof(IB))]
public IB B2 { private get; set; }
}
However, MEF isn't really designed for such fine-grained control over the composition. You could try an alternative like Autofac, which integrates well with MEF.
I don't entirely understand what you are trying to do, but I think you may be able to do it by specifying a creation policy of NonShared on the IB import.
[Import(RequiredCreationPolicy=CreationPolicy.NonShared)]
public IB B;