Use a class in two different namespace - c#

How do use a class from namespace in other namespace?
namespace All
{
class X
{
public static void Read() {}
}
class Y
{
public static void Write() {}
}
}
namespace A
{
namespace First{
//use class X in namespace All here;
}
}
namespace B
{
namespace Second{
//use class Y in namespace All here;
}
}
i don't want copy paste code,is there a keyword in C# to reference the hole the class? use it here like
B.Second.Y.Write();

you cannot directly use other types as variable in a namespace
So
You may use those types (X, Y) in the types in those namespaces (First, Second). e.g
namespace All
{
class X
{
public static void Read() { }
}
class Y
{
public static void Write() { }
}
}
namespace A
{
namespace First
{
//use class X in namespace All here;
}
}
namespace B
{
namespace Second
{
//use class Y in namespace All here;
class MyClass
{
private All.X; //HERE is the code
}
}
}

Try the using Keyword
using A;
using B;
using All;

If you define namespace A & B as followed:
namespace All
{
public class X
{
public static void Read() { }
}
public class Y
{
public static void Write() { }
}
}
namespace A
{
namespace First
{
public static class X
{
public static void Read()
{
All.X.Read();
}
}
}
}
namespace B
{
namespace Second
{
public static class Y
{
public static void Write()
{
All.Y.Write();
}
}
}
}
You can then use it like so...
namespace CodeResearch.StackOverFlowTests
{
using System;
/// <summary>
/// Defines DebugStackOverFlow type
/// </summary>
public class DebugStackOverFlow
{
/// <summary>
/// Tests debugging StackOverFlow questions
/// </summary>
public static void Test()
{
A.First.X.Read();
B.Second.Y.Write();
Console.ReadLine();
}
}
}
NOTE:
I have all of this defined in the same cs file.

Related

how to get all previous called methods from first to end methods

Let's say we have this code
namespace app.Entities
{
public class school
{
public bool Addschool() { }
}
}
namespace app.layer1
{
public class ManageSchool
{
public bool schoolInfo() {
schoolInfo.addSchool();
}
}
}
namespace app.layer
{
public class schoolAPi
{
public bool GetAndAdd()
{
ManageSchool.schoolInfo();
}
}
}
i want to know which layers and fuctions called AddSchool() method in app.entitied namespace
for exp :
app.layer2.schoolAPi.GetAndAdd >> app.layer1.ManageSchool.schoolInfo >> app.Entities.school.Addschool
Try look at System.Diagnostics.StackTrace and System.Diagnostics.StackFrame classes.
You can create some Tracer class with Trace method to trace each call, but you supposed to put trace in each method to be able to trace it.
Example of Tracer.cs:
using System.Diagnostics;
public class Tracer
{
public static void Trace()
{
StackFrame sf = new StackTrace(true).GetFrame(1);
Console.WriteLine("Called {0} in {1} at line: {2}", sf.GetMethod().ToString(), sf.GetFileName(), sf.GetFileLineNumber());
}
}
Examples of your project:
Entities.cs:
namespace App.Entities
{
public class School
{
public static bool AddSchool()
{
Tracer.Trace();
return true;
}
}
}
LayerOne.cs:
using App.Entities;
namespace App.LayerOne
{
public class ManageSchool
{
public static bool SchoolInfo()
{
Tracer.Trace();
School.AddSchool();
return true;
}
}
}
LayerTwo.cs:
using App.LayerOne;
namespace App.LayerTwo
{
public class SchoolAPI
{
public static bool GetAndAdd()
{
Tracer.Trace();
ManageSchool.SchoolInfo();
return true;
}
}
}
And a Program.cs:
using System;
using App.LayerTwo;
namespace App
{
class Program
{
static void Main(string[] args)
{
Tracer.Trace();
SchoolMethod();
Console.ReadKey();
}
static void SchoolMethod()
{
Tracer.Trace();
SchoolAPI.GetAndAdd();
}
}
}
It will give you some kind of this result:
Also you can put Tracer.Trace() method under bool condition of some global setting and use it only when you need trace:
if (MySettingsClass.TraceEnabled)
Tracer.Trace();

What is the required parameter for casting C#

Minimal reproducible example
Base abstract class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace YangHandlerTool
{
public abstract class YangNode
{
public string Name { get; set; }
/// <summary>
/// This is here to force YangNode constructor with Name parameter.
/// </summary>
private YangNode() { }
public YangNode(string name) { Name = name; }
}
}
Child that adds "Type" property
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace YangHandlerTool
{
public class Leaf : YangNode
{
public string Type { get; set; }
public Leaf(string leafname) : base(leafname){ }
}
}
Other Child that adds "Type" property
using System;
namespace YangHandlerTool
{
public class LeafList : YangNode
{
public string Type { get; set; }
public LeafList(string leafname) : base(leafname) { }
}
}
Main
using System;
using System.Collections.Generic;
namespace YangHandlerTool
{
class Program
{
static void Main(string[] args)
{
List<YangNode> yangnodes = new List<YangNode>();
yangnodes.Add(new Leaf("leafname"));
for (int i = 0; i < yangnodes.Count; i++)
{
if (IsLeaf(i))
{
///I want to call SetTypeOfNode with the intention to cast to Leaf
SetTypeOfNode(yangnodes[i]);
}
if (IsLeafList(i))
{
///I want to call SetTypeOfNode with the intention to cast to LeafList
SetTypeOfNode(yangnodes[i]);
}
}
}
private static void SetTypeOfNode(YangNode inputnode)
{
///Desired
//Replace GIVENANYCLASSNAME with any given classname as parameter
//((GIVENANYCLASSNAME)inputnode).Type = "value";
((Leaf)inputnode).Type = "value";
}
/// <summary>
/// It is 100% guaranteed that the item is a Leaf.
/// </summary>
private static bool IsLeaf(int index)
{
return index == 0;
}
private static bool IsLeafList(int index)
{
return index == 1;
}
}
}
In the function "private static void SetTypeOfNode(YangNode inputnode)" I want to be able to give a Class as parameter what to cast to. In order to spare 100+ line in my actual program of casting like:
((Leaf)inputnode).Type = "value";
((LeafList)inputnode).Type = "value";
((AnothertypeInheritedfromYangnode)inputnode).Type = "value";
((AnothertypeInheritedfromYangnode2)inputnode).Type = "value";
...
How can you pass a Classname as parameter that can be given into the casting parameter?

How to call function inside custom attribute class

Lets say i have the following attribute class.
//Attribute Implementation
public abstract class TestAttribute : Attribute
{
public abstract void UpdateSomething(string s);
}
public class CustomAttTest : TestAttribute
{
private State state;
public CustomAttTest(State state)
{
this.state = state;
}
public override void UpdateSomething(string s)
{
if (state.Equals(State.First))
{
Console.WriteLine("First State!! " + s);
}
}
}
public enum State
{
First, Second, Third
}
How can i call the Updatesomthing function inside the attribute class?
following is the attribute implementation example.
public abstract class Vehicle
{
//Coode
}
[CustomAttTest(State.First)]
public class Ferrari : Vehicle
{
//Code
}
Here is the full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var foo = new Ferrari();
//How do i call the UpdateSomething implemented insde the CustomAttTest attribute class?
}
}
public abstract class Vehicle
{
//Coode
}
[CustomAttTest(State.First)]
public class Ferrari : Vehicle
{
//Code
}
//Attribute Implementation
public abstract class TestAttribute : Attribute
{
public abstract void UpdateSomething(string s);
}
public class CustomAttTest : TestAttribute
{
private State state;
public CustomAttTest(State state)
{
this.state = state;
}
public override void UpdateSomething(string s)
{
if (state.Equals(State.First))
{
Console.WriteLine("First State!! " + s);
}
}
}
public enum State
{
First, Second, Third
}
}
You need to use reflection:
foo.GetType().GetCustomAttribute<CustomAttTest>().UpdateSomething(...);
However, you should probably use an abstract method or property instead of an attribute.

Derived types with Method overloading

The code is simple enough to understand I hope.
I'm trying to use an interface type IColor in order to pass color objects to the ColorManager. I then want the ColorManager to pass this object to the IColor object as its own type, so the method overloads gets called.
However, it seems since it is being passed as the IColor type, C# will not implicity cast it into its complete type as either a BlueColor or GreenColor.
I hope this makes some sense to somebody on what I want to achieve. Is this possible in C#?
[Solution]
http://msdn.microsoft.com/en-us/library/dd264736.aspx
Overload Resolution with Arguments of Type dynamic
My code so far:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
namespace Example
{
public interface IColor
{
void CatchColor(IColor c);
}
public class BlueColor : IColor
{
public void CatchColor(IColor c)
{
}
}
public class GreenColor : IColor
{
public void CatchColor(BlueColor c)
{
Console.WriteLine("CAUGHT BLUE!");
}
public void CatchColor(GreenColor c)
{
Console.WriteLine("CAUGHT GREEN!");
}
public void CatchColor(IColor c)
{
Console.WriteLine("CAUGHT SOME COLOR!");
}
}
public class ColorManager
{
public void PassColor(IColor c)
{
// Don't use static type-checking
// Problem solved
dynamic AnyColor = c;
AnyColor.CatchColor(AnyColor);
}
public static void Main()
{
GreenColor G = new GreenColor();
new ColorManager().PassColor(G);
Console.ReadLine();
return;
}
}
}
One possiblity to tell the ColorManager class to use the correct type of the passed object is to use an abstract class, that already implements the CatchColor:
public abstract class IColor
{
// override in every class
public abstract void PrintColor();
// has the correct type passed with the interface
public void CatchColor(IColor c)
{
c.PrintColor();
}
}
Then the sub classes need to implement only PrintColor with the correct color:
public class BlueColor : IColor
{
public override void PrintColor()
{
Console.WriteLine("BLUE!");
}
}
public class GreenColor : IColor
{
public override void PrintColor()
{
Console.WriteLine("GREEN!");
}
}
The manager is the same:
public class ColorManager
{
public void PassColor(IColor c)
{
c.CatchColor(c);
}
}
It can be used like this:
GreenColor G = new GreenColor();
var cm = new ColorManager();
cm.PassColor(G);
cm.PassColor(new BlueColor());
The outputs is:
GREEN!
BLUE!
What you want is late method binding.
The downside to this is you have to add methods for each new type of color. The upside is you don't have to maintain a case statement or conditional logic.
See here for more detail:
Early and late binding
Edit: Here is a working example of this type of late-binding.
class Program {
static void Main(string[] args) {
//Declare instances
BaseClass myClass = new Class2();
BaseClass otherClass = new Class1();
//Invoke the action method which will match based on the BaseClass type
Action(myClass);
Action(otherClass);
Console.ReadLine();
}
public static void Action(BaseClass classType) {
//Remove the compile-time type so the runtime can select the method based on signature
dynamic aClass = classType;
ServiceMethod(aClass);
}
public static void ServiceMethod(dynamic input) {
Methods(input);
}
public static void Methods(Class1 classType) {
Console.WriteLine("Class1");
Debug.WriteLine("Class1");
}
public static void Methods(Class2 classtype) {
Console.WriteLine("Class2");
Debug.WriteLine("Class2");
}
public static void Methods(Class3 classType) {
Console.WriteLine("Class3");
Debug.WriteLine("Class3");
}
}
public abstract class BaseClass { //This could also be an interface
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Class1 : BaseClass {
}
public class Class2 : BaseClass{
}
public class Class3 : BaseClass {
}
So you want something like:
public void CatchColor(Color c)
{
if (c is BlueColor)
CatchColor(c as BlueColor);
if (c is GreenColor)
CatchColor(c as GreenColor);
}
?

C#: Access Enum from another class

I know I can put my enum at the Namespace area of a class so everyone can access it being in the same namespace.
// defined in class2
public enum Mode { Selected, New, }
What I want is to access this enum from
public class1
{
var class2 = new class2();
// Set the Mode
class2.Mode = Model.Selected
}
Is this somehow possible without using namespace area?
You can declare an enum outside of a class:
namespace MyNamespace
{
public enum MyEnum
{
Entry1,
Entry2,
}
}
And then you can add using MyNamespace; where it needs to be used.
Aaron's answer is very nice but I believe there is a much better way to do this:
public static class class1
{
public void Run()
{
class2.Mode mode = class2.Mode.Selected;
if (mode == class2.Mode.Selected)
{
// Do something crazy here...
}
}
}
public static class class2
{
public enum Mode
{
Selected,
New
}
}
No point over complicating this. It is a simple task.
All the Best
Chris.
If you are trying to do what is described below it will not work...
public class MyClass1
{
private enum Mode { New, Selected };
public Mode ModeProperty { get; set; }
}
public class MyClass2
{
public MyClass2()
{
var myClass1 = new MyClass1();
//this will not work due to protection level
myClass1.ModeProperty = MyClass1.Mode.
}
}
What you could do however is below, which will work...
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;
}
}
Yes:
class2.Mode = class2.Mode.Selected
But note that you can't have a nested type defined that has the same name as one of the outer class' members, so this code will not compile. Either the enum or the property will need to be named something else. Your class name and variable name conflict too, making this a bit more complex.
To make this a more generic answer, if you have this:
public class Foo
{
public SomeEnum SomeProperty { get; set; }
public enum SomeEnum {
Hello, World
}
}
Then this code will assign an enum value to the property:
Foo foo = new Foo();
foo.SomeProperty = Foo.SomeEnum.Hello;
I ended up solving my issue by changing it to a namespace accessor, found by utilizing Intellisense. I thought the enum was in the class, not just the namespace. If it was in the class, I would recommend moving it out of the class.
namespace ABC.XYZ.Contracts
{
public class ChangeOrder : BaseEntity, IAuditable
{
...
}
public enum ContractorSignatureType
{
A,
B,
V
}
}
ContractorSignatureType = Contracts.ContractorSignatureType.B,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace #enum
{
class temp
{
public enum names
{
mohitt,
keval,
Harshal,
nikk
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine((int)temp.names.nikk);
Console.ReadKey();
}
}
}
//by using this you can access the value of enum.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace #enum
{
class temp
{
public enum names
{
mohitt,
keval,
Harshal,
nikk
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(temp.names.nikk);
Console.ReadKey();
}
}
}

Categories

Resources