I have the following code:
class EmployeeFactory
{
public enum EmployeeType
{
ManagerType,
ProgrammerType,
DBAType
}
}
I want to access this in MAIN class (Program). I have written the following code. IT WORKS. But I want to know how I can access the ENUM without instantiating the class -- Means ENUM is like a static variable (Class Level Variable) ? Any help ?
class Program
{
static void Main(string[] args)
{
Console.WriteLine(EmployeeFactory.EmployeeType.ProgrammerType); // WORKS WELL
}
}
or do I need to write it this way?
EmployeeFactory ef = new EmployeeFactory();
ef.EmployeeType.ProgrammerType
You can access it simply using the class.
EmployeeFactory.EmployeeType.ProgrammerType
The enum is part of the class, not part of a class instance.
But I want to know how I can access the ENUM without instantiating the class
The original way you're accessing this enum
Console.WriteLine(EmployeeFactory.EmployeeType.ProgrammerType);
already accomplishes that; you are accessing the enum without instantiating the class.
try something like this ...
public interface IEnums
{
public enum Mode { New, Selected };
}
public class MyClass1
{
public IEnums.Mode ModeProperty { get; set; }
}
public class MyClass2
{
public MyClass2()
{
var myClass1 = new MyClass1();
//this will work
myClass1.ModeProperty = IEnums.Mode.New;
}
}
or
you can directly access like this....
EmployeeFactory.EmployeeType.ProgrammerType
i hope it will helps you
Related
Hi trying to make a class inside a static class to use in JINT but when it's referenced I get an error
C# code
namespace Hi {
public static class Ok {
public class Wowa {
public Wowa(){}
}
}
}
But when I try to make a new one in JavaScript I get an error "the object cannot be used as a constructor" from JINT
var k = new Hi.Ok.Wowa()
Am I doing this right? How can I set up the C# to be able to use the above code in JavaScript from JINT?
BTW IF instead of "Ok" being a static class, rather a namespace, it works, but I want it as a class because I want to have static methods in it also
you cant use none-static class in a static class (ReadThis) but if you remove (static) in your frist class
namespace Hi {
public class Ok {
public class Wowa {
public Wowa(){}
}
}
}
and it can be said that it does not make much difference because (Static) only makes subcategories of your class have to use (Static).
But if you want your class to be impossible to build on variables, you can use abstract(ReadThis)
namespace Hi {
public abstract class Ok {
public class Wowa {
public Wowa(){}
}
}
}
and
Main()
{
Ok k = new Ok();//Error
}
Imagine you have this:
namespace Hi
{
public static class Ok
{
public class Wowa
{
public Wowa() { }
public static string MyStaticMethod() => "Hello from 'Static Method'";
public string MyNormalMethod() => "Hello from 'Normal Method'";
}
}
}
It's possible to use non-static class Wowa by making an instance of it , and then you can call MyNormalMethod of that instance (you can only call not-static method within instance of that class).
Hi.Ok.Wowa wowa = new Hi.Ok.Wowa();
wowa.MyNormalMethod();
And without making any instance of Wowa you can call static method within it, like this:
Hi.Ok.Wowa.MyStaticMethod();
Finally you can see working code here.
class TestA{
some code.....
}
class TestB{
.....
}
class Program{
void Main(){
TestA obj= new TestB();////When and why do we sometimes do this?
}
}
What are the different scenarios when we would have to refer one object to another class?
We don't. We created a variable called obj, and declared the variable to be of type TestA. That means that that variable can contain a reference to any object this IS-A TestA.
You then create a TestB object. Presumably, TestB derives from TestA, which is not shown in your question. But that means that this new object, is, generally, a TestA, as well as being, specifically, a TestB. We then assign a reference to this object to the obj variable.
Which is fine. It still is a TestB object. It's just that this code, clearly, doesn't intend to use any of it's B-ish nature. Just the core A-ish part that it shares; It's also possible that the TestB class overrides some of TestA's members, in which case it will still demonstrate it's B-ish nature when those members are accessed.
From your code example this approach could be used if TestB inherits from TestA. If you're unsure what inheritance is you should read a bit about Object Oriented programming. Another approach where you would have a class which creates other objects is if you are using a Factory Pattern. There's plenty of information on the web about this pattern too. If you are using a factory pattern you wouldn't use the same constructor approach as in your code though (i.e. you wouldn't expect a new instance of an object to return a different object.)
the answer to this as much as i know, this could be in two cases:
1-Polymorphism.
2-Interfaces.
I'll show u how:
Polymorphism is like :
//an example of Polymorphism.
class FamilyMembers //parent class
{
public virtual void GetData() //it's virtual method cuz it can be overridden later
{
Console.WriteLine("Family");
}
}
class MyBrother : FamilyMembers //child class
{
public override void GetData() //the same method that we wrote before has been overridden
{
Console.WriteLine("Bro");
}
}
class Program
{
static void Main(string[] args)
{
//here's what u asking about
FamilyMembers myBrother = new MyBrother(); //MyBrother is a family member, the system now will choose the GetData() method from the child class MyBrother
myBrother.GetData();
Console.ReadLine();
}
}
Interface is like:
public interface IFamily //the Parent Class
{
//an interface holds the signature of it's child properties and methods but don't set values
//Some properties signatures
int Age { get; set; }
string Name { get; set; }
//some methods
void PrintData();
}
public class MyBrother : IFamily //Child class that inherits from the parent class
{
//some properties, methods, fields
public string Name { get; set; } //public required
public int Age { get; set; } //public required
private string Collage { get; set; } //for my brother only
//constractor that sets the default values when u create the class
public MyBrother()
{
Name = "Cody";
Age = 20;
Collage = "Faculty of engineering";
}
////a method
void IFamily.PrintData()
{
Console.WriteLine("Your name is: " + Name + " and your age is: " + Age + " and you collage is: " + Collage);
}
}
class Program
{
static void Main(string[] args)
{
//now let's try to call the the methods and spawn the child classes :)
//spawn the child class (MyBrother) that inherits from the Family interface
//this is the answer of ur question
IFamily myBrother = new MyBrother(); // the constructor will auto-set the data for me so i don't need to set them
//printing the dude
myBrother.PrintData();
Console.ReadLine();
}
}
I hope this will do :)
We can only do this when class have parent-child relationship,Otherwise it can't be possible to assign one class memory to another class.
Read More...1
Read More...2
I am trying to figure out a way I can make use of private static fields in a generic class. This is the obvious way to do it (fiddle). It won't compile because Field is not accessible in BaseChild, and ideally I wouldn't want it to be accessible there:
public class Base<T>
{
private static readonly string Field = "field";
public Base()
{
Console.WriteLine(Field);
}
}
public class BaseChild : Base<string>
{
public BaseChild()
{
Console.WriteLine(Field);
}
}
The problem with this solution is that there is a different Field for each generic type, instead of being shared across them.
I have seen this answer where it says that JetBrains recommends a solution for static fields across generic types:
If you need to have a static field shared between instances with different generic arguments, define a non-generic base class to store your static members, then set your generic type to inherit from this type.
This makes sense for the case where you have public or protected static fields in the base class that you want to share across any child class like this example (fiddle):
public abstract class Base
{
protected static readonly string Field = "field";
}
public class Base<T> : Base
{
public Base()
{
Console.WriteLine(Field);
}
}
public class BaseChild : Base<string>
{
public BaseChild()
{
Console.WriteLine(Field);
}
}
However, what about the case where you want to use a private static field? I would guess that this is not possible since private means only accessible to the class it's declared in and I think that since the generic class is really just a template to create a class, that any private field could only ever be shared by each class, not across all the classes created by the template.
Do I have to just put the private field in the generic class (example 1) and accept it as at least a workable solution for what I want, or is there another way I can accomplish this?
First off -- private is doing exactly what it's made to do: to restrict access to only the type it was declared in. Keep in mind that instantiations of a generic type are all distinct types. You shouldn't be wanting to work around this.
If I understand your question correctly, you can accomplish what you want by using protected with an extra level of inheritance:
class EvenMoreBase
{
protected static readonly string Field = "field";
}
class Base<T> : EvenMoreBase
{
public Base()
{
Console.WriteLine(Field);
}
}
class BaseChild : Base<string>
{
public BaseChild()
{
Console.WriteLine(Field);
}
}
Now each of your Base<T> will share the same instance of Field.
You're correct in your thoughts on private within the base class. Whether it is static or not makes no difference.
Here's a little example:
using System;
public class Program
{
public static void Main()
{
Bar b = new Bar(); // Prints "Foo"
// Console.WriteLine(Foo.BaseField); // Compile error
}
}
public class Foo
{
protected static readonly string BaseeField = "Foo";
}
public class Bar : Foo
{
public Bar()
{
Console.WriteLine(Foo.BaseeField);
}
}
Marking it protected is useful, if you'd like only your children to be able to access it. And leaving it static is how you'd keep only one instance around for all children of the base Foo class.
This is something I came up with that I think actually does what I want better than the initial example I put in my question. It shares a single static field across all the generic types, and it is inaccessible from children of the Base generic class.
public static class Base
{
private static string Field = "field";
public class Base2<T>
{
public Base2()
{
// Field is accessible here, but is the same across all generic classes
Console.WriteLine(Field);
}
}
}
public class BaseChild : Base.Base2<string>
{
public BaseChild()
{
//Field is not accessible here, and I don't really want it to be
//Console.WriteLine(Field);
}
}
I wrote the following console app to test static properties:
using System;
namespace StaticPropertyTest
{
public abstract class BaseClass
{
public static int MyProperty { get; set; }
}
public class DerivedAlpha : BaseClass
{
}
public class DerivedBeta : BaseClass
{
}
class Program
{
static void Main(string[] args)
{
DerivedBeta.MyProperty = 7;
Console.WriteLine(DerivedAlpha.MyProperty); // outputs 7
}
}
}
As this console app demonstrates, the MyProperty property exists once for all instances of BaseClass. Is there a pattern to use which would allow me to define a static property which will have allocated storage for each sub-class type?
Given the above example, I would like all instances of DerivedAlpha to share the same static property, and all instances of DerivedBeta to share another instance of the static property.
Why am I trying to do this?
I am lazily initializing a collection of class property names with certain attributes (via reflection). The property names will be identical for each derived class instance, so it seems wasteful to store this in each class instance. I can't make it static in the base class, because different sub-classes will have different properties.
I don't want to replicate the code which populates the collection (via reflection) in each derived class. I know that one possible solution is to define the method to populate the collection in the base class, and call it from each derived class, but this is not the most elegant solution.
Update - Example of what I'm doing
At Jon's request, here's an example of what I'm trying to do. Basically, I can optionally decorate properties in my classes with the [SalesRelationship(SalesRelationshipRule.DoNotInclude)] attribute (there are other attributes, this is just a simplified example).
public class BaseEntity
{
// I want this property to be static but exist once per derived class.
public List<string> PropertiesWithDoNotInclude { get; set; }
public BaseEntity()
{
// Code here will populate PropertiesWithDoNotInclude with
// all properties in class marked with
// SalesRelationshipRule.DoNotInclude.
//
// I want this code to populate this property to run once per
// derived class type, and be stored statically but per class type.
}
}
public class FooEntity : BaseEntity
{
[SalesRelationship(SalesRelationshipRule.DoNotInclude)]
public int? Property_A { get; set; }
public int? Property_B { get; set; }
[SalesRelationship(SalesRelationshipRule.DoNotInclude)]
public int? Property_C { get; set; }
}
public class BarEntity : BaseEntity
{
public int? Property_D { get; set; }
[SalesRelationship(SalesRelationshipRule.DoNotInclude)]
public int? Property_E { get; set; }
public int? Property_F { get; set; }
}
Desired end result
Accessing FooEntity.PropertiesWithDoNotInclude returns a List<string> of:
{
"Property_A",
"Property_C"
}
Accessing BarEntity.PropertiesWithDoNotInclude returns a List<string> of:
{
"Property_E"
}
Two possible approaches:
Use attributes; decorate each subclass with an attribute, e.g.
[MyProperty(5)]
public class DerivedAlpha
{
}
[MyProperty(10)]
public class DerivedBeta
{
}
That only works when they're effectively constants, of course.
Use a dictionary:
var properties = new Dictionary<Type, int>
{
{ typeof(DerivedAlpha), 5) },
{ typeof(DerivedBeta), 10) },
};
EDIT: Now that we have more context, Ben's answer is a really good one, using the way that generics work in C#. It's like the dictionary example, but with laziness, thread-safety and simple global access all built in.
Jon has a good solution as usual, although I don't see what good attributes do here, since they have to be explicitly added to every subtype and they don't act like properties.
The Dictionary approach can definitely work. Here's another way to do that, which explicitly declares that there will be one variable per subclass of BaseEntity:
class FilteredProperties<T> where T : BaseEntity
{
static public List<string> Values { get; private set; }
// or static public readonly List<string> Values = new List<string>();
static FilteredProperties()
{
// logic to populate the list goes here
}
}
The drawback of this is that it's rather difficult to pair with a GetType() call such as you might use in methods of BaseEntity. A Dictionary, or wrapper thereto which implements lazy population, is better for that usage.
I just recently needed this same thing and came across this question. I think Jon's and Fried's ideas to use a Dictionary are on the right track but don't quite hit what I was looking for so I thought I'd show my own complete and very easy to extend implementation.
public class TypeStaticProperty<T>
{
T _defaultValue;
Dictionary<Type, T> _values = new Dictionary<Type, T>();
public TypeStaticProperty(T defalutValue = default)
{
_defaultValue = defalutValue;
}
public T Get(object caller)
{
lock (_values)
{
if (_values.TryGetValue(caller?.GetType(), out T val))
return val;
else
return _defaultValue;
}
}
public void Set(object caller, T val)
{
lock (_values)
_values[caller?.GetType()] = val;
}
}
And to demonstrate:
class TestBaseClass
{
static TypeStaticProperty<int> _property = new TypeStaticProperty<int>();
public int Property
{
get => _property.Get(this);
set => _property.Set(this, value);
}
}
class TestClass1 : TestBaseClass
{
}
class TestClass2 : TestBaseClass
{
}
class Program
{
static void Main(string[] args)
{
TestClass1 test1a = new TestClass1();
TestClass1 test1b = new TestClass1();
test1a.Property = 1;
test1b.Property = 2;
TestClass2 test2a = new TestClass2();
TestClass2 test2b = new TestClass2();
test2a.Property = 3;
test2b.Property = 4;
Console.WriteLine($"test1a.Property = {test1a.Property}");
Console.WriteLine($"test1b.Property = {test1b.Property}");
Console.WriteLine($"test2a.Property = {test2a.Property}");
Console.WriteLine($"test2b.Property = {test2b.Property}");
}
}
Output:
test1a.Property = 2
test1b.Property = 2
test2a.Property = 4
test2b.Property = 4
So while you still need a class instance to access and set the property, the value will always be the same across all instances of that precise type. (This includes generics too; Foo<int> will be seen as a different type than Foo<string>). This has the huge advantage over Fried's example in that you don't need to know at compile time the precise type whose "static" value you're looking for when accessing or setting.
PS - For full disclosure, this was heavily inspired by the WPF source code, which uses a very similar pattern for DependencyProperty's and all kinds of other internal bells and whistles designed to improve performance and reduce memory footprint.
This is a noob question
using System.name;
class class_name
{
private className Obj;
public class_name()
{
}
public function()
{
Obj.function <----- why i cant acesss the global varible here ??
}
}
When i type the class the instellisence docent show any thing :-s
I'm assuming there was just some confusion with the names and, by function, you meant class_name, or instead of class_name you meant className.
In order to access a method this way, it must be declared as static. Otherwise, you must first create an instance of the class and access the method through the instance.
EDIT The code you posted is very confusing. The following works just fine for me.
class Class1
{
public void Function1()
{
}
}
class Class2
{
private Class1 obj;
public void Function2()
{
obj.Function1();
}
}
Have you instantiated that class?