may I ask (as a novice) how do I call a method of a namespace, from another? Thank you for setting up an example if possible..
For example: (1) how do I set the properties of the MY_PRIMARY class to use them and (2) how do I call the AddNumbers method while in the MY_SECONDARY namespace? Thank you..
using.. etc
namespace MY_PRIMARY
{
public partial class SomethingHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
private static void Main()
{
// some code here.. and..
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
}
};
namespace MY_SECONDARY
{
public partial class SomethingElseHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
static void Main()
{
// some code here..
}
// and..
Program outer = new Program();
outer.AddNumbers(3, 18); // <--- this is failing..
}
}
;
Namespaces are meant to group objects semantically. I'm kind of confused why you have 2 program classes. It would make more sense to have one class library, and one program. Anyway...
Suppose you have an Object1 in namespace Program.First,
And an Object2 in Program.Second
Object2 has a method named someMethod.
What you would do to call this method is
a) either add "using Program.Second", on you first class.
b) make an instance of Program.Second.Object2, and call the method on that.
https://www.programiz.com/csharp-programming/namespaces
So suppose you want to make an object of Program() do this:
using System;
namespace MY_PRIMARY
{
public partial class SomethingHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
public class Program
{
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
}
}
namespace MY_SECONDARY
{
public partial class SomethingElseHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
static void Main()
{
MY_PRIMARY.Program outer = new MY_PRIMARY.Program();
outer.AddNumbers(3, 18);
}
}
}
(EDIT) updated my answer, i copied your code and saw that your namespaces were not closed off, therefor, you had nested namespaces, and classes in there. plus, some of the code was directly in your class instead of in a function.
Also, don't define 2 Main() methods, that's the entrypoint of the application.
...A little modification in POSITIONS of functions and classes... please, see:
using Alias = MY_PRIMARY.Program;
namespace MY_PRIMARY
{
public partial class SomethingHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
public class Program
{
private static void Main()
{
// some code here.. and..
}
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
};
namespace MY_SECONDARY
{
public partial class SomethingElseHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
static void Main()
{
// some code here..
// and..
Alias outer = new Alias();
outer.AddNumbers(3, 18); // <--- OKAY...
}
}
}
}
See more:
Using namespaces (C# Programming Guide)
see my code :
public interface IStructureType
{
int Longueur { get; set; }
int Position { get; set; }
int CompleterCodeBy { get; set; }
}
public abstract class StructureTypeFactory
{
public abstract IStructureType GetStructureType(string type);
}
public class ConcreteStructureTypeFactory : StructureTypeFactory
{
public override IStructureType GetStructureType(string type)
{
switch(type)
{
case "StructureCodeMagasin":
return new StructureCodeMagasin();
case "StructureChrono":
return new StructureChrono();
case "StructureLotSimple":
return new StructureLotSimple();
default:
throw new ApplicationException("");
}
}
}
public class StructureCodeMagasin : IStructureType
{
public int Longueur { get ; set; }
public int Position { get; set; }
public int CompleterCodeBy { get { return 2; } set { CompleterCodeBy = value; } }
public void GetCodeMagasin()
{
//some code
}
}
I try to use Factory pattern, but how I can access to method GetCodeMagasin in this example :
public MainWindow()
{
InitializeComponent();
StructureTypeFactory st = new ConcreteStructureTypeFactory();
var structure = st.GetStructureType("StructureCodeMagasin");
int longueur = structure.CompleterCodeBy;
}
I can access properties but no method, I would like structure variable will typed StructureCodeMagasin.
Thanks for help
fans of beautiful code.
I would like to ask my question by two ways. May be it will be useful to understand me.
1) There is code of 2 classes. One of them is nested. Nested class is used to get access to private fields of other one. I would like to get inherit class B:A{class BUnit:AUnit{}} which has the same functional but else has some more methods and fields in B and BUnits classes. How it can be done?
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Add();
a.Add();
a.Add();
bool res=a[0].Rename("1");//res=true;
res = a[1].Rename("1");//res= false;
Console.ReadKey();
}
}
class A
{
private List<AUnit> AUnits;
public AUnit this[int index] {get {return AUnits[index];}}
public A()//ctor
{
AUnits = new List<AUnit>();
}
public void Add()
{
this.AUnits.Add(new AUnit(this));
}
public class AUnit
{
private string NamePr;
private A Container;
public AUnit(A container)//ctor
{
NamePr = "Default";
this.Container = container;
}
public string Name { get { return this.NamePr; } }
public Boolean Rename(String newName)
{
Boolean res = true;
foreach (AUnit unt in this.Container.AUnits)
{
if (unt.Name == newName) res = false;
}
if (res) this.NamePr = String.Copy(newName);
return res;
}
}
}
2) There is two very similar “things” – Class A and Class B. Is it possible to separate their common part, and then “inherit” this two “things” from it ? For example, I would like add some methods like GetUnitsCount() or RemoveUnit() and this methods are common for both. So I should “CopyPaste” this method to A and B but it is not good idea. It will be better to change their common part one time in one place. There is no important how it can be done – inheriting or interfaces or anything else. Important - how?
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Add();
a[0].objB.Add();
a[0].objB.Add();
a[0].objB[0].Val1 = 1;
int res = a[0].objB[0].Val1 + a[0].objB[0].Val2;
Console.ReadKey();
}
}
class A
{
private List<AUnit> Units;
public AUnit this[int index] {get {return Units[index];}}
public A()//ctor
{
Units = new List<AUnit>();
}
public void Add()
{
this.Units.Add(new AUnit(this));
}
public class AUnit
{
private string NamePr;
private A Container;
public B objB;
public AUnit(A container)//ctor
{
NamePr = "Default";
this.Container = container;
this.objB = new B();
}
public string Name { get { return this.NamePr; } }
public Boolean Rename(String newName)
{
Boolean res = true;
foreach (AUnit unt in this.Container.Units)
{
if (unt.Name == newName) res = false;
}
if (res) this.NamePr = String.Copy(newName);
return res;
}
}
}
class B
{
private List<BUnit> Units;
public BUnit this[int index] { get { return Units[index]; } }
public B()//ctor
{
Units = new List<BUnit>();
}
public void Add()
{
this.Units.Add(new BUnit(this));
}
public class BUnit
{
private string NamePr;
private B Container;
public int Val1{get;set;}
public int Val2{get;set;}
public BUnit(B container)//ctor
{
NamePr = "Default";
this.Container = container;
this.Val1 = 10;
this.Val2 = 17;
}
public string Name { get { return this.NamePr; } }
public Boolean Rename(String newName)
{
Boolean res = true;
foreach (BUnit unt in this.Container.Units)
{
if (unt.Name == newName) res = false;
}
if (res) this.NamePr = String.Copy(newName);
return res;
}
}
}
Thank you for your attentions.
To answer your first question, the only thing you need to to to have BUnit inherit from AUnit is to qualify AUnit:
public class BUnit : A.AUnit
{
....
}
from there I believe your question is about basic inheritance which works no differently for nested classes. Nested classes are purely for organization - they are not inherited when you inherit the "containing" class.
This question already has answers here:
Virtual member call in a constructor
(18 answers)
Closed 8 years ago.
Is it wrong to initialize a virtual property in the constructor? It just does not feel right because if you override the property in a derived class the property will first be initialized with the value from the base class constructor then it will be assigned again by the derived class constructor. is there an alternative for doing this? I'm talking about something like this
internal class B1
{
public B1()
{
Ti = "Hello";
}
public virtual string Ti { get; set; }
}
internal class B2 : B1
{
public B2()
{
Ti = "HelloKitty";
}
public override string Ti { get; set; } //<--"Hello" will be assigned first then "HelloKitty" will be assigned
}
internal class Program
{
private static void Main(string[] args)
{
var b2 = new B2();
Console.WriteLine(b2.Ti);
Process.GetCurrentProcess().WaitForExit();
}
}
UPDATE 1:
As recommended by #AK_
internal class Bb1
{
private string _ti;
public Bb1()
{
_ti = "Hello";
}
public virtual string Ti
{
get { return _ti; }
set { _ti = value; }
}
}
internal sealed class Bb2 : Bb1
{
public Bb2()
{
Ti = "HelloKitty";
}
public override string Ti { get; set; }
}
the variable _ti in the base class is initialized by "Hello".
what if instead of string type I'm using type which explicitly needs to be exposed?
On the other hand this is reasonable (notice that B2 is sealed )
internal class B1
{
private string m_ti;
public virtual string Ti { get{return m_ti;} set{m_ti = value;} }
public B1()
{
m_ti = "Hello";
}
}
internal sealed class B2 : B1
{
public B2()
{
Ti = "HelloKitty";
}
public override string Ti { get; set; } //<--"Hello" will be assigned first then "HelloKitty" will be assigned
}
another option a protected constructor:
internal class B1
{
private string m_ti;
public virtual string Ti { get { return m_ti; } set { m_ti = value; } }
public B1()
{
m_ti = "Hello";
}
protected B1(String word)
{
m_ti = word;
}
}
internal sealed class B2 : B1
{
public B2():base("kitty")
{
}
}
Please excuse bursts of stupidity as I learn the intricacies of C# / .NET
Say I have three classes with multiple static properties (more than three but for arguments sake..)
CLASS FOO
public static A
{
get / set A;
}
public static B
{
get / set B;
}
public static C
{
get / set C;
}
CLASS BAR
{
get / set A;
}
public static B
{
get / set B;
}
public static C
{
get / set C;
}
CLASS YOO
{
get / set A;
}
public static B
{
get / set B;
}
public static C
{
get / set C;
}
And from another class I need to update one or several static properties in each class multiple times... How do I keep from writing multiple SWITCH statments like this...
public void updateVarx(string class, string varx)
{
string y = 'class'
SWITCH (y)
{
case FOO:
FOO.A = Varx;
break;
case BAR:
BAR.A = Varx;
break;
case YOO:
YOO.A = Varx;
break;
}
}
And then another one when I want to update B varY:
public void updateVary(string class, string vary)
{
string y = 'class'
SWITCH (y)
{
case FOO:
FOO.B = Vary;
break;
case BAR:
BAR.B = Vary;
break;
case YOO:
YOO.B = Vary;
break;
}
}
Since you are learning .net/c#, I guess i should warn you, using static properties is probably not the way to go in object oriented programming.
Static is global state and is dangerous. If you end up using multi-threaded code, you have to be super careful. If you need only one instance, just instantiate one, but don't go creating static properties on a class, unless you have a pretty good reason to add them (And I can't think of any right now).
In fact, in well designed, object oriented code you sould probably not have many if, switch, getters or setters either.
Let's say you need different behaviors on your classes, you can do it this way.
Interface ISecurity {
void UpdateVarX(int value);
void UpdateVarY(int value);
int GetValueX();
int GetValueX();
}
class Foo:ISecurity {
// Implement methods of the interface
}
class Bar:ISecurity {
// Implement methods of the interface
}
class Yoo:ISecurity {
// Implement methods of the interface
}
// This class is the class that uses your other classes
class Consumer
{
private ISecurity sec;
public Consumer(ISecurity sec) {
sec.UpdateVarX(25);
}
}
Or if as in your example, all your static classes have the same properties:
public class Settings {
public int A {get; set;}
public int B {get; set;}
public int C {get; set;}
}
public class NeedsToUseOtherClass {
public NeedsToUseOtherClass() {
Settings foo = new Settings();
Settings bar = new Settings();
Settings yoo = new Settings();
foo.setA(25);
}
}
Maybe I am not understanding the problem but if all your classes have the same exact properties then you can just pass the object (FOO, BAR, or YOO) into UpdateVarx or UpdateVary methods and just implement an interface? Something along these lines:
public class FOO : IHasStatus
{
public A
{
get / set A;
}
public B
{
get / set B;
}
public C
{
get / set C;
}
}
public void updateVarx(IHasStatus someObject, string varx)
{
someObject.A = varx;
}
public void updateVary(IHasStatus someObject, string vary)
{
someObject.B = vary;
}
If you don't need the concrete classes, you can abstract out the logic like so:
public class Status {
public string A {
get; set;
}
public string B {
get; set;
}
public string C {
get; set;
}
}
public static class StatusManager {
private static Dictionary<string, Status> statusMap = new Dictionary<string,Status>();
public static Status GetStatus(string name) {
Status status;
if (!statusMap.TryGetValue(name, out status))
statusMap[name] = status = new Status();
return status;
}
public static void SetStatus(string name, Status status) {
statusMap[name] = status;
}
public static void UpdateVarx(string name, string varx) {
GetStatus(name).A = varx;
}
// ...
}
If you are a fan of the javascript way of solving multiple switch cases like this
you can always wrap up the switch handlers as Actions and toss them in a Dictionary.
For example : (Source obtained from here)
public class SwitchCase : Dictionary<string,Action>
{
public void Eval(string key)
{
if (this.ContainsKey(key))
this[key]();
else
this["default"]();
}
}
//Now, somewhere else
var mySwitch = new SwitchCase
{
{ "case1", ()=>Console.WriteLine("Case1 is executed") },
{ "case2", ()=>Console.WriteLine("Case2 is executed") },
{ "case3", ()=>Console.WriteLine("Case3 is executed") },
{ "case4", ()=>Console.WriteLine("Case4 is executed") },
{ "default",()=>Console.WriteLine("Default is executed") },
};
mySwitch.Eval(c);
Below code uses all kinds of hacks, not really recommended in production code unless you have a very good reason.
using System;
using System.Linq;
namespace ConsoleApplication1
{
static class Program
{
private static void SetStaticProperty(string className, string propName, string varx)
{
//This sucks, I couldnt find the namespace with easily through reflection :(
string NAMESPACE = "ConsoleApplication1";
Type t = Type.GetType(NAMESPACE + "." + className);
t.GetProperties().Where(p => p.Name == propName).First().SetValue(null, varx, null);
}
public static void updateVarx(string className, string varx)
{
SetStaticProperty(className, "A", varx);
}
public static void updateVary(string className, string vary)
{
SetStaticProperty(className, "B", vary);
}
static void Main(string[] args)
{
updateVarx("Foo", "FooAstring");
updateVarx("Bar", "BarAstring");
updateVarx("Yod", "YodAstring");
updateVary("Foo", "FooBstring");
updateVary("Bar", "BarBstring");
updateVary("Yod", "YodBstring");
Console.WriteLine(Foo.A);
Console.WriteLine(Foo.B);
Console.WriteLine(Bar.A);
Console.WriteLine(Bar.B);
Console.WriteLine(Yod.A);
Console.WriteLine(Yod.B);
Console.ReadLine();
}
}
class Foo
{
public static string A { get; set; }
public static string B { get; set; }
public static string C { get; set; }
}
class Bar
{
public static string A { get; set; }
public static string B { get; set; }
public static string C { get; set; }
}
class Yod
{
public static string A { get; set; }
public static string B { get; set; }
public static string C { get; set; }
}
}
You can use dictionary as configuration and remove the switch statement
Create a dictionary and add append data as below for mapping
//Have dictionary setted up
Dictionary<string, dynamic> m_Dictionary = new Dictionary<string, dynamic>();
m_xmlDictionary.Add("classA",FOO);
m_xmlDictionary.Add("classB",BAR);
m_xmlDictionary.Add("classC",BAR);
//Have dictionary setted up
//change the function as below
public void updatevarx(string class, string varx)
{
m_Dictionary[class].A=varx // Replaced switch statement
}
//while calling use
updatevarx("classC","abc!");// This will assign BAR.A with abc!