using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3Generics
{
class Program
{
static void Main(string[] args)
{
ScheduleSelectedItems sitems = new ScheduleSelectedItems("Yusuf");
ScheduleSelectedItemsList slist = new ScheduleSelectedItemsList();
slist.Items.Add(sitems);
Console.Write(slist.Items[0].ToString());
Console.ReadKey();
}
}
public class ScheduleSelectedItems
{
private string Ad;
public ScheduleSelectedItems(string ad)
{
Ad = ad;
}
}
public class ScheduleSelectedItemsList
{
public List Items;
public ScheduleSelectedItemsList()
{
Items = new List();
}
}
}
how can i add "yusuf" on my Console?
public class ScheduleSelectedItems
{
private string Ad;
public ScheduleSelectedItems(string ad)
{
Ad = ad;
}
public override string ToString()
{
return this.Ad;
}
}
What BFree said, with a slight modification to make it singular instead of plural:
public class ScheduleSelectedItem
{
private string Ad;
public ScheduleSelectedItem(string ad)
{
Ad = ad;
}
public override string ToString()
{
return this.Ad;
}
}
Additionally, you want an "Add" method for your list. While you're at it, why not just inherit from the list class:
public class ScheduleSelectedItemsList : List<ScheduleSelectedItem>
{
}
Or you could just create a type alias:
using ScheduleSelectedItemsList = List<ScheduleSelectedItem>;
Either way, you can use the new code like this:
class Program
{
static void Main(string[] args)
{
var slist = new ScheduleSelectedItemsList()
{
new ScheduleSelectedItem("Yusuf")
};
//write every item to the console, not just the first
slist.All(item => Console.Write(item.ToString()) );
Console.ReadKey();
}
}
Add this to your ScheduleSelectedItems class:
public override string ToString() {
return Ad;
}
That tells the system how such an object should be formatted.
You need to override the toString() method of ScheduleSelectedItems to return 'Ad'.
Related
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();
I have a class in my project and I want to instantiate it only once by passing a specific parameter via the constructor, but when I pass different parameter it should instantiate a new one. How I can achieve this with the singleton design pattern? Or can you suggest another design pattern if it can't be achieved with a singleton?
class Program
{
static void Main()
{
SiteStructure s = SiteStructure.Instance;
}
}
public sealed class SiteStructure
{
static readonly SiteStructure _instance = new SiteStructure();
public static SiteStructure Instance
{
get
{
return _instance;
}
}
SiteStructure()
{
// Initialize.
}
}
You have to modify the way the _instance variable is initialised, making use of a function that accepts the parameter value that you want to pass in. Also, the _instance variable can no longer be readonly as it needs to be initialised inside of the new function.
[TestMethod]
public void CreateSingletonInstance()
{
SiteStructure s = SiteStructure.GetInstance("Abc123");
Debug.Print(s.Parameter); // outputs Abc123
SiteStructure s2 = SiteStructure.GetInstance("Is it really a singleton?");
Debug.Print(s2.Parameter); // outputs Is it really a singleton?
SiteStructure s3 = SiteStructure.GetInstance("Abc123");
Debug.Print(s3.Parameter); // outputs Abc123
Assert.AreNotEqual(s, s2); // Check to make sure they are different instances
Assert.AreEqual(s, s3); // Check to make sure they are the same instance
}
public sealed class SiteStructure
{
static Dictionary<string, SiteStructure> _siteStructures = new Dictionary<string, SiteStructure>();
static object _instance_Lock = new object();
public static SiteStructure GetInstance(string parameter)
{
if (!_siteStructures.ContainsKey(parameter))
{
lock (_instance_Lock)
{
if (!_siteStructures.ContainsKey(parameter))
{
_siteStructures.Add(parameter, new SiteStructure(parameter));
}
}
}
return _siteStructures[parameter];
}
private SiteStructure(string parameter)
{
// Initialize.
Parameter = parameter;
}
public string Parameter { get; set; }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var g = SiteStructure.Instance(4);
}
}
public sealed class SiteStructure {
public static SiteStructure Instance()
{ return new SiteStructure();
}
public static SiteStructure Instance (int x)
{ return new SiteStructure (x);
}
SiteStructure() { }
SiteStructure(int x) { Console.WriteLine("Hello"); }
}
}
I'm playing with VS. I'm a rookie, It must be basic. I have created 2 classes and I puzzled with result. I'm using Visual Studio 2015 community edition.
I'm expect to receive at console :
myfirstClass
Class
first.
mysecondClass
Class
second.
I received :
myfirstClass
Class
_
class Program
{
public class mysecondClass
{
static public string myName ;
public mysecondClass()
{
Console.WriteLine("mysecondClass");
myName = "Class";
}
public static void Display()
{
Console.WriteLine(myName);
}
~mysecondClass()
{
Console.WriteLine("second.");
}
}
public class myfirstClass
{
public string myName;
public myfirstClass()
{
Console.WriteLine("myfirstClass");
myName = "Class";
}
public static void Display()
{
myfirstClass d = new Program.myfirstClass();
Console.WriteLine(d.myName);
}
~myfirstClass()
{
Console.WriteLine("first.");
}
}
static void Main(string[] args)
{
myfirstClass.Display();
mysecondClass.Display();
Console.ReadLine();
}
}
This is not a bug in Visual Studio. I think you have got two concepts wrongly.
Firstly, the finaliser of a class will not be called immediately after the object is out of scope. It will be called at a random time. It is quite unpredictable.
Therefore, this:
Console.WriteLine("first.");
is not printed.
The second thing is that constructors of a class is only called when you write new XXX(...) (or through reflection). Just calling a static method will not invoke the constructor.
In other words, these lines are never executed:
Console.WriteLine("mysecondClass");
myName = "Class";
You never wrote new mysecondClass().
When this line in the display method of mysecondClass executes:
Console.WriteLine(myName);
Since myName has not been assigned, it is null, and so nothing is printed.
class Program
{
public class mysecondClass
{
public string myName { get; set; }
public mysecondClass()
{
Console.WriteLine("mysecondClass");
myName = "Class";
}
public static void Display()
{
var mySecond = new mysecondClass();
Console.WriteLine(mySecond.myName);
}
~mysecondClass()
{
Console.WriteLine("second.");
}
}
public class myfirstClass
{
public string myName { get; set; }
public myfirstClass()
{
Console.WriteLine("myfirstClass");
myName = "Class";
}
public static void Display()
{
myfirstClass d = new myfirstClass();
Console.WriteLine(d.myName);
}
~myfirstClass()
{
Console.WriteLine("first.");
}
}
static void Main(string[] args)
{
myfirstClass.Display();
mysecondClass.Display();
Console.ReadLine();
}
}
try this
I have a class P as part of namespace D with several fields and related properties
namespace Driver
[Export(typeof (P))]
public class Pilot : Send
{
private bool _b1;
...
public bool B1
{
get { return _b1; }
private set
{
if (_b1 != value)
{
_b1 = value;
NotifyOfPropertyChange(() => B1);
}
}
}
And then another class in the same namespace with some methods
namespace Driver
public class PilotEng
{
public void Statistics()
{
....
}
public void Running()
{
....
}
What is the best way to access and use the parameters of class P in class PE methods?
There are many ways for PilotEng to access information from Pilot.
Pass in instance of Pilot at PilotEng construction:
public class PilotEng
{
private Pilot myPilot;
public PilotEng(Pilot pilot)
{
myPilot = pilot;
}
public void Statistics()
{
var whatever = myPilot.B1;
....
}
public void Running()
{
....
}
}
somewhere else...
public void SomeMethod()
{
Pilot p = new Pilot();
PilotEng pe = new PilotEng(p);
pe.Statistics();
}
update your method signature(s) to take in an instance of pilot to work with:
public class PilotEng
{
public void Statistics(Pilot pilot)
{
var whatever = pilot.B1;
....
}
public void Running()
{
....
}
}
somewhere else...
public void SomeMethod()
{
Pilot p = new Pilot();
PilotEng pe = new PilotEng();
pe.Statistics(p);
}
Both are valid, one may be more valid than another, and there are several other ways to accomplish this. It all depends on what you're actually trying to do.
I have two classes as follow:
First one:
class Class1
{
private void Method1()
{
var obj=new TestClass();
obj.TestMethod1();
}
}
Second One:
class TestClass
{
public void TestMethod1()
{
TestMethod2();
}
private void TestMethod2()
{
//get the calling class
}
}
When Class1.Method1 calls TestClass.TestMethod1 which in turn calls TestClass.TestMethod2, I want to get the fully qualified class name of Class1 inside TestClass.TestMethod2. I have seen this link, but I think I will get TestClass.TestMethod1 as method name and TestClass as the class name. How can I get the calling class name?
There is no nice way to do that. You can access the stack-frames (just look at the second frame, rather than the first) - but that is expensive and brittle. You could use optional caller-member-name attributes (being explicit from TestMethod1) to get hold of "Method1", but not the "Class1" part. One other option would be to pass in an object (or just the name) explicitly; for example:
private void Method1()
{
var obj=new TestClass();
obj.TestMethod1(this);
}
public void TestMethod1(object caller=null,
[CallerMemberName] string callerName=null)
{
TestMethod2(caller??this,callerName??"TestMethod1");
}
private void TestMethod2(object caller=null,
[CallerMemberName] string callerName=null)
{
string callerName = ((caller??this).GetType().Name) + "." + callerName
//get the calling class
}
but I have to confess that is pretty ugly
Perhaps better would be to question why you need this in the first place.
Could you not pass the type into the second class via constructor like:
class Class1
{
private void Method1()
{
Type t = typeof(Class1);
var obj = new TestClass(t);
obj.TestMethod1();
}
}
class TestClass
{
private Type _caller;
public TestClass(Type type)
{
_caller = type;
}
public void TestMethod1()
{
TestMethod2();
}
private void TestMethod2()
{
//Do something with the class
}
}
You might check out this code to find your solution without having to pass class instances or type parameters, etc....:
class Program
{
static void Main(string[] args)
{
var c = new Class1();
c.Method1();
}
}
class Class1
{
public void Method1()
{
var obj = new TestClass();
obj.TestMethod1();
}
}
class TestClass
{
public void TestMethod1()
{
TestMethod2();
var mth = new StackTrace().GetFrame(1).GetMethod();
var clss = mth.ReflectedType.Name;
Console.WriteLine("Classname in Method1(): {0}", clss);
}
private void TestMethod2()
{
//get the calling class
var mth = new StackTrace().GetFrame(1).GetMethod();
var clss = mth.ReflectedType.Name;
Console.WriteLine("Class in .Method2(): {0}", clss);
}
}
This will get the Type that first called TestClass. It prints:
TestStack.Class1
TestStack.Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace TestStack
{
class Class1
{
public void Method1()
{
var obj = new TestClass();
obj.TestMethod1();
}
}
class TestClass
{
public void TestMethod1()
{
TestMethod2();
}
private void TestMethod2()
{
StackTrace st = new StackTrace();
Type calling = null;
foreach (var sf in st.GetFrames())
{
var type = sf.GetMethod().DeclaringType;
if (type != this.GetType())
{
calling = type;
break;
}
}
Console.WriteLine(calling);
}
}
class Program
{
static void Main(string[] args)
{
Class1 class1 = new Class1();
class1.Method1();
TestClass testClass = new TestClass();
testClass.TestMethod1();
}
}
}