Is it somehow possible that base class can access fields in inherited class (has-a relationship)?
class BasicClass
{
public InheritedClass objTemp = new InheritedClass();
public BasicClass()
{
//Now i want to get some information from objTemp fields.
//But Name is protected, what should I do here?
objTemp.Name.Length();
}
}
class InheritedClass
{
protected string Name;
}
Maybe there are some tricky things that I don't know how to manage, or maybe it is better to create some more clever class hierarchy. Anyway thank you in advance.
Sorry for missunderstanding.In few words i have class Game which consist another class WordsContainer.
class Game
{
private Player objGamer;
private WordsContainer objWordsClass = new WordsContainer();
public Game()
{
Console.Title = "Hangman";
Console.Write("Player name information:");
string localName = Console.ReadLine();
objGamer = new Player(localName);
StringBuilder bumpWord = new StringBuilder(objWordsClass.getKeyWord().Length);
}
class WordsContainer
{
/// <summary>
/// WordsContainer class contains a list of strings from wich with getKeyWord method
/// we could get string type key.
/// </summary>
private List<string> wordBank = new List<string>() {"stack","queue","heap","git","array"};
public WordsContainer(){}
public string getKeyWord()
{
Random random = new Random((int)DateTime.Now.Ticks);
return wordBank[random.Next(0, wordBank.Count)];
}
So is it possible in this way somehow hide public string getKeyWord().
If you want to keep going on the code you have now, you could just define a public string GetName() function in InheritedClass and call it from the object that you create in the BasicClass
class BasicClass
{
public InheritedClass objTemp = new InheritedClass();
public BasicClass()
{
int nameLength = objTemp.GetName().Length();
}
}
class InheritedClass
{
protected string Name;
public string GetName()
{
return Name;
}
}
Related
I have 2 classes StaggingAttorney and Attorney. I will use the StaggingAttorney to collect information about an attorney and once I have all the information I will use it to create an Attorney profile using the best results. The 2 classes look like this;
private class StaggingAttorney : CourtCase.Attorney
{
public bool scraping = false;
public bool scraped = false;
public string caseNumber;
public CourtCase.Attorney toAttorney()
{
CourtCase.Attorney attorney = new CourtCase.Attorney();
return attorney;
}
}
...and...
public class Attorney
{
public string names;
public string matchString;
...
public List<Identity> IdentityMatches = new List<Identity>();
public List<Identity> getIdentityMatches()
{
return IdentityMatches;
}
public class Identity
{
public string names;
public string barNumber;
public string email;
public string phoneNumber { get; internal set; }
public object faxNumber { get; internal set; }
}
}
I have created a method called CourtCase.Attorney toAttorney() which you can see above. In this method I want to return a new CourtCase.Attorney with all CourtCase.Attorney inherited properties in the the StaggingAttorney
As #derloopkat suggested, you can simply cast your "StaggingAttorney" instance to his parent class. ("Attorney" in this case)
But if you really need a new instance of an "Attorney" with the same values than the parent "StaggingAttorney" just access to the parent fields of your "StaggingAttorney" object.
private class StaggingAttorney : CourtCase.Attorney
{
public bool scraping = false;
public bool scraped = false;
public string caseNumber;
public CourtCase.Attorney toAttorney()
{
CourtCase.Attorney attorney = new CourtCase.Attorney()
{
names = this.names,
matchString = this.matchString,
[... Initialize the other properties ...]
};
return attorney;
}
}
When you create an instance of a child class you are also creating the parent. So there are no many scenarios where you need to make another new instance from a child.ToParent() method. Having a conversion method like this makes more sense when one class is not inheriting from the other.
var attorney = new StaggingAttorney() { scraped = false };
attorney.names = "John"; //During the scraping process
attorney.scraped = true;
CourtCase.Attorney court = (CourtCase.Attorney)attorney; //casting
Console.WriteLine(court.names); //returns "John"
No need to copy data, because the child inherited names from its parent.
I would like to pass values from one class file to another class.
E.g:
Step1:
Class1.cs
public class Class1
{
public string LogedInPerson { get; set; }
public string Name
{
get { return this.LogedInPerson; }
set { this.LogedInPerson = value; }
}
}
Step2:
Value has been assigned in below method:
test.xaml.cs
public void assignValue()
{
Class1 obj = new Class1();
obj.LogedInPerson = "test123";
}
Step3:
I would like to get "test123" values from Class2.cs.
E.g:
public void test()
{
string selected_dept = ?? //How to get "test123" from here.
}
You can have variables class that includes public variables. Define instance of class1 in variables class .
public static class1 myclass=new class1();
in test.xml.cs set value
public void assignValue()
{
myclass.LogedInPerson = "test123";
}
in class2.cs
public void test()
{
string selected_dept = myclass.LogedInPerson;
}
Initialize Class1 outside assignValue() methos
Class1 obj = new Class1();
public void assignValue()
{
obj.LogedInPerson = "test123";
}
public string returnValue()
{
return obj.LogedInPerson;
}
if your second class name test.xaml then call it like this, but I don't think you can use class name test.xaml so use a nice name instead there eg: Class2
public void test()
{
test.xaml test = new test.xaml();
test.assignValue();
string selected_dept = test.returnValue(); //How to get "test123" from here.
}
I believe this question is more on the topic of basic Object Oriented Programming principles, not so much about WPF specific features. Therefore, I will provide you a non-WPF specific answer, as it will allow me to address your question in the most direct way.
In OOP, a method can return a result to the caller. So, for instance,
public string GetReturnObject(){
return "This is a return object";
}
You can create a new object and pass it back to the caller,
public void Test(){
string data = GetReturnObject();
}
And now data will be assigned the object that was returned from the method that Test() called. So, if you modify your AssignValue method by adding a return type and passing the instantiated Class1 object back to the caller, you will have the answer you need
public Class1 assignValue()
{
Class1 obj = new Class1();
obj.LogedInPerson = "test123";
return obj;
}
Hope that helps.
I currently have the following problem:
I have a class which includes 3 different fields
Enum x
ActiveDirectoryUser y
CustomClass z
The enum can be initialised by passing a string or the enum object.
The ADUser can be initialised by passing a string (LoginName) or the user by itself and the CustomClass can be initialized by passing a string, int or the object.
Now I want to initialize the class to pass all different combinations like
class(string enumValue, string adUser, string customClass)
class(string enumValue, ADUser adUser, CustomClass customClass)
class(EnumValue enumValue, string adUser, CustomClass customClass)
Is there a way to simplify the constructors without typing all of the 12 possibilities (Enum-2 * ADUser-2 * CClass-3 = 12)?
I thought about chained constructors where i also ended up with 12 constructors but also thought about just passing the c# Object on each parameter and cast it and do stuff with it but i think that is just a dirty workaround?
Edit
The class is contained in an library and so can be used internal but also public. For the internal uses there is no problem to pass a concrete version of an object.
But if i use it public in other solutions these solutions can only refer to string or int values. So the class should be able to 'take' the values and convert them while beeing initialised because it have access to all the real objects.
Maybe this clarifies the problem a bit.
Here some code snippets with changed names:
#region Content of libraryOne
public class ClassName
{
internal EnumValueWrapper { get; set; }
internal CustomClass { get; set; }
internal ADUser { get; set; }
public ClassName() { ... } //Now via Builder Pattern
internal ClassName() { ... } //With Parameters for internal initialisations
public InformationContainer GetContentInfo()
{
//[...]Process Stuff and Return Container
}
}
internal CustomClass { ... }
internal EnumValueWrapper { ... }
internal ADUser { ... }
#endregion Content of libraryOne
If your class has only 3 properties (EnumValue, ADUser, CustomClass) then you should have only one constructor with these :class(EnumValue enumValue, ADUser adUser, CustomClass customClass). The ADUser and CustomClass should be instantiated outside of your class using their constructor which support string or int, etc;
Example:
class (EnumValue param, new ADUser(string_param), new CustomClass(int_param));
class (EnumValue param, new ADUser(ADUser_param), new CustomClass(string_param));
Edit
You can use it like I described above for internal scope and for the public part you can use and expose a factory (wrapper) class which actually can receive users and other parameters as strings or int and internally instantiate and return your class.
In addition to your snippet: Create a proxy like public class in your assembly that can be accessed from outside (from other assemblies).Make your class internal:
public class ClassNameBuilder
{
private ClassName _className;
public ClassNameBuilder(string enumValue, string user, string custom_class)
{
_className = new ClassName(EnumToString, new User(user), new CustomClass(custom_class));
}
public void CallClassNameMethod1()
{
return _className.Method1()
}
public void CallClassNameMethod2()
{
return _className.Method2()
}
}
The builder class can use whatever method you want to build the ClassName object; This way you can expose all your class methods without using multiple constructors.
I think the best thing to do is use the Builder pattern. You can even use it with derived classes.
My classes to build:
public class MyBaseClass
{
public MyBaseClass(SomeEnum enumValue, User user)
{
}
}
public class MyDerivedClass : MyBaseClass
{
public MyDerivedClass(SomeEnum enumValue, User user, CustomClass customStuff)
: base(enumValue, user)
{
}
}
Now let's add a builder class featuring an additional extension class for making things much more comfortable (it's sort of an extended Builder pattern using C# extension method wizadry):
public class MyBaseClassBuilder
{
public SomeEnum EnumValue { get; set; }
public User User { get; set; }
}
public static class MyBaseClassBuilderExtensions
{
public static T SetEnumValue<T>(this T instance, SomeEnum value)
where T : MyBaseClassBuilder
{
instance.EnumValue = value;
return instance;
}
public static T SetEnumValue<T>(this T instance, string value)
where T : MyBaseClassBuilder
{
instance.EnumValue = (SomeEnum)Enum.Parse(typeof(SomeEnum), value);
return instance;
}
public static T SetUser<T>(this T instance, User value)
where T : MyBaseClassBuilder
{
instance.User = value;
return instance;
}
public static T SetUser<T>(this T instance, string value)
where T : MyBaseClassBuilder
{
instance.User = new User(value);
return instance;
}
public static MyBaseClass Build(this MyBaseClassBuilder instance)
{
return new MyBaseClass(instance.EnumValue, instance.User);
}
}
Now let's do the same thing for our derived class:
public class MyDerivedClassBuilder : MyBaseClassBuilder
{
public CustomClass CustomStuff { get; set; }
}
public static class MyDerivedClassBuilderExtensions
{
public static T SetCustomStuff<T>(this T instance, CustomClass value)
where T : MyDerivedClassBuilder
{
instance.CustomStuff = value;
return instance;
}
public static T SetCustomStuff<T>(this T instance, string value)
where T : MyDerivedClassBuilder
{
instance.CustomStuff = new CustomClass(value);
return instance;
}
public static MyDerivedClass Build(this MyDerivedClassBuilder instance)
{
return new MyDerivedClass(instance.EnumValue, instance.User, instance.CustomStuff);
}
}
Now you can construct your instances in some fluent API style way:
static void Main(string[] args)
{
MyBaseClass baseInstance = new MyBaseClassBuilder()
.SetEnumValue("Alpha")
.SetUser("Big Duke")
.Build();
MyDerivedClass derivedInstance = new MyDerivedClassBuilder()
.SetEnumValue(SomeEnum.Bravo)
.SetUser(new User("Lt. Col. Kilgore"))
.SetCustomStuff("Smells like victory")
.Build();
}
Finally the additional types:
public enum SomeEnum
{
Alpha,
Bravo
}
public class User
{
public User(string name)
{
this.Name = name;
}
public string Name { get; private set; }
}
public class CustomClass
{
public CustomClass(string notation)
{
this.Notation = notation;
}
public string Notation { get; private set; }
}
This way you can construct instances which require many constructor arguments in a comfortable way.
I need the separate classes for Xml Serialization. I'd like to know if there is a simpler way for the inheriting BuildingDetail class to acquire the property values from the parent Building class.
Parent Class
public class Building
{
public int BuildingId;
public string BuildingName;
protected Building()
{
}
private Building(int buildingId, string buildingName)
{
BuildingId = buildingId;
BuildingName = buildingName;
}
public static Building Load(int buildingId)
{
var dr = //DataRow from Database
var building = new Building(
(int) dr["BuildingId"],
(string) dr["BuildingName"]);
return building;
}
}
Inheriting Class
public class BuildingDetail : Building
{
public BaseList<Room> RoomList
{
get { return Room.LoadList(BuildingId); }
}
protected BuildingDetail()
{
}
// Is there a cleaner way to do this?
private BuildingDetail(int buildingId, string buildingName)
{
BuildingId = buildingId;
BuildingName = buildingName;
}
public new static BuildingDetail Load(int buildingId)
{
var building = Building.Load(buildingId);
var buildingDetail = new BuildingDetail(
building.BuildingId,
building.BuildingName
);
return buildingDetail;
}
}
Thanks.
Firstly, change your base class constructor access modifier to protected. And then you can call base class constructor with base keyword:
private BuildingDetail(int buildingId, string buildingName)
: base(buildingId, buildingName)
{
...
}
It will call the base constructor first. Also if you don't put the :base(param1, param2) after your constructor, the base's empty constructor will be called.
I have a static Class and within it I have multiple public static attributes. I treat this class as my global class.
However now I need to treat this class as a variable so that I can pass it to a method of another class for processing..
I can't instantiate this class.. So in effect I can only assign the variables inside this class.
Is my understanding correct or am I missing something?
public static class Global
{
public const int RobotMax = 2;
// GUI sync context
public static MainForm mainForm;
public static SynchronizationContext UIContext;
// Database
public static Database DB = null;
public static string localDBName = "local.db";
public static Database localDB = null;
public static Database ChangeLogDB = null;
public static string changeLogDBName = "ChangeLog.db";
}
Let say I have a class like this, and I need to somehow keep a copy of this in another class maybe
public static class Global_bk
{
public const int RobotMax = 2;
// GUI sync context
public static MainForm mainForm;
public static SynchronizationContext UIContext;
// Database
public static Database DB = null;
public static string localDBName = "local.db";
public static Database localDB = null;
public static Database ChangeLogDB = null;
public static string changeLogDBName = "ChangeLog.db";
}
I need to copy the contents from Global to Global_bk.
And after that I need to compare the contents of the two classes in a method like
static class extentions
{
public static List<Variance> DetailedCompare<T>(T val1, T val2)
{
List<Variance> variances = new List<Variance>();
FieldInfo[] fi = val1.GetType().GetFields();
foreach (FieldInfo f in fi)
{
Variance v = new Variance();
v.Prop = f.Name;
v.valA = f.GetValue(val1);
v.valB = f.GetValue(val2);
if (!v.valA.Equals(v.valB))
variances.Add(v);
}
return variances;
}
}
class Variance
{
string _prop;
public string Prop
{
get { return _prop; }
set { _prop = value; }
}
object _valA;
public object valA
{
get { return _valA; }
set { _valA = value; }
}
object _valB;
public object valB
{
get { return _valB; }
set { _valB = value; }
}
}
So on my main form, how do I go about calling the compare method and passing the static Global class inside?
example: extentions.DetailedCompare(Global, Global_bk) ? Of course this would give me an error because I cant pass a type as a variable.
Please help me, this is driving me nuts...
How about the singleton pattern ? You can pass reference to shared interface (IDoable in exable below) and still have just one instance.
I.E.:
public interface IDoable {
int Value { get; set; }
void Foo();
}
public static class DoableWrapper {
private MyDoable : IDoable {
public int Value { get;set; }
public void Foo() {
}
}
private static IDoable s_Doable = new MyDoable();
public static IDoable Instance {
get { return s_Doable; }
}
}
Singleton is the way to go here. You can do it like this:
internal class SomeClass
{
private static SomeClass singleton;
private SomeClass(){} //yes: private constructor
public static SomeClass GetInstance()
{
return singleton ?? new SomeClass();
}
public int SomeProperty {get;set;}
public void SomeMethod()
{
//do something
}
}
The GetInstance Method will return you a SomeClass object that you can edit and pass into whatever you need.
You can access the members with classname.membername.
internal static class SomeClass
{
public static int SomeProperty {get;set;}
public static void SomeMethod()
{
//do something
}
}
static void main()
{
SomeClass.SomeProperty = 15;
SomeClass.SomeMethod();
}
The only way you are going to obtain a variable with the "class" information is using reflection. You can get a Type object for the class.
namespace Foo {
public class Bar
{
}
}
Type type = Type.GetType("Foo.Bar");
Otherwise, if you are really describing a class "instance" then use an object and simply instantiate one.
C# offers no other notation for class variables.