I've got two windows(MainWindow,SecondWindow), one class (ExampleClass) in ExampleClass two strings (Name,SecondName) and method with messagebox which should contains text from Name + SecondName variables.
So i want to add some text from MainWindow to ExampleClass Name string and then some text from opened SecondWindow to ExampleClass SecondName string. After that i want to click on MainWindow button and that should give me messagebox with both of strings
Name + SecondName
MainWindow :
ExampleClass SomeClass = new ExampleClass();
SomeClass.Name = MainWindowTxtBox.Text;
Second Window :
ExampleClass SomeClass = new ExampleClass();
SomeClass.SecondName = SecondWindowTxtBox.Text;
This will create new istance of class only for one window, is it possible to create istance for both Windows?
You can use static like this:
class ExampleClass
{
public static string Name { get; set; }
public static string SecondName { get; set; }
public static void print()
{
MessageBox.Show(Name + SecondName);
}
}
Then in MainWindow:
ExampleClass.Name = MainWindowTxtBox.Text;
And in the SecondWindow:
ExampleClass.SecondName = SecondWindowTxtBox.Text;
And finally:
ExampleClass.print();
Yes this is possible. But one class needs to know the other class. Try it like this:
Class1
{
public ExampleInstance Instance { get; set; }
//Create your Class2 object here with Class2 SecondClassObject = new Class2(this)
}
Class2
{
private Class1 MyCreator;
public Class2(Class1 Creator)
{
this.MyCreator = Creator;
}
//Now you can use the object with: MyCreator.Instance
}
Hope this helps.
You should then create the instances of your class in the main application instead of the windows.
Create a singleton (https://msdn.microsoft.com/en-us/library/ff650316.aspx):
public class ExampleClass
{
public string Name { get; set; }
public string SecondName { get; set; }
protected ExampleClass() {
}
static ExampleClass _instance;
public static ExampleClass Instance {
get {
return _instance ?? (_instance = new ExampleClass());
}
}
}
and your code will look like this:
MainWindow
ExampleClass.Instance.Name = MainWindowTxtBox.Text;
Second Window
ExampleClass.Instance.SecondName = SecondWindowTxtBox.Text;
Related
I want to use textBox1.Text in a different class not just in the main where the text boxes are defined so to say. Is there any way to make it global? Because it only allows me to use it in the main thing, not in the seperate class that I have to make in my task.
I need to store the text from the textBox in a List that is in a different class so the user can't add the same name twice so I need to remember what was typed in in the first input.
This is the class where I created a List and where I want to store those inputs:
internal class Clanovi
{
public static List<Clan> Dodaj()
{
List<Clan> clanovi = new List<Clan>();
clanovi.Add(new Clan() { KorIme = textBox1.Text, Lozinka = textBox2.Text });
return clanovi;
}
}
class Clan
{
public string KorIme { get; set; }
public string Lozinka { get; set; }
}
This is WinForm btw.
Your variable names are in another language so it is hard to understand but I think you want this
internal class Clanovi
{
public static List<Clan> Dodaj()
{
Global.clanovi.Add(new Clan() { KorIme = textBox1.Text, Lozinka = textBox2.Text });
// you don't need to return this since it is already global
return clanovi;
}
}
public static class Global
{
public static List<Clan> clanovi = new List<Clan>();
}
public static class Clan
{
public static string KorIme { get; set; }
public static string Lozinka { get; set; }
}
Whenever you want to access your global variables, you use the Global class with the static items in it.
i suggest to:
change the modifiers property in the properties of the textbox to public.
write this code in the other class :
Form_name/class_name myTextbox = new form_name/class_name();
ex:
Form1 myTextbox = new Form1();
now u can use in any other class/form: mytextbox.Textbox.text.
internal class Clanovi
{
Clan myTextbox = new Clan();
public static List<Clan> Dodaj()
{
List<Clan> clanovi = new List<Clan>();
clanovi.Add(new Clan() { KorIme = myTextbox.textBox1.Text, Lozinka = textBox2.Text });
return clanovi;
}
}
C# Newbie Here.
I have a class below:
namespace CompanyDevice.DeviceResponseClasses
{
public class DeviceStatusClass
{
public class Root
{
public static string RequestCommand { get; set; }
}
}
}
In another namespace I have:
namespace CompanyDevice
{
public class StatusController : ApiController
{
public DeviceStatusClass Get()
{
var returnStatus = new DeviceStatusClass();
returnStatus.Root.RequestCommand = "Hello"; //'Root' is causing a CS0572 error
return returnStatus;
}
}
}
I'm sure I'm making some rudimentary error here. Could you please help me find it? Thanks.
You access static properties from the type, not from the instance.
DeviceStatusClass.Root.RequestCommand = "Command";
Because the property RequestCommand is static, there will only ever be one. Perhaps this is what you want, but likely is not based on your usage.
You can remove the static keyword from RequestCommand, then you can access it through the instance, however you will need to add a field or property for the instance of Root inside of DeviceStatusClass.
public class DeviceStatusClass
{
public Root root = new Root();
public class Root
{
public string RequestCommand { get; set; }
}
}
And use like you did originally.
public class StatusController : ApiController
{
public DeviceStatusClass Get()
{
var returnStatus = new DeviceStatusClass();
returnStatus.root.RequestCommand = "Hello";
return returnStatus;
}
}
You maybe have a java background. In c# nested classes only change the names, they do not make the parent class contain an instance of a child class
namespace CompanyDevice.DeviceResponseClasses
{
public class DeviceStatusClass
{
public class Root
{
public static string RequestCommand { get; set; }
}
public Root DeviceRoot {get;set;} <<<=== add this
}
}
and then
returnStatus.DeviceRoot.RequestCommand = "Hello";
I am looking for a way to have an object in a class and make it non-editable (the object itself AND its properties) outside the class itself but still visible outside.
internal class Room
{
public string Description { get; set; }
}
internal class RoomController
{
public Room Room { get; private set; }
public RoomController()
{
Room = new Room();
}
//Edit the room inside this class
}
internal class Foo
{
public void SomeMethod()
{
RoomController rc = new RoomController();
rc.Room.Description = "something"; // This should not be allowed
string roomDesc = rc.Room.Description; // This should be fine
}
}
Is something like that possible? I couldn't find anything regarding the issue so I would be grateful if anyone has any ideas.
Thanks in advance!
You could define an interface that only exposes the bits you want public:
internal interface IReadonlyRoom
{
string Description { get; } //note only getter exposed
}
internal class Room : IReadonlyRoom
{
public string Description { get; set; }
}
internal class RoomController
{
private Room _room;
public IReadonlyRoom Room => _room;
public RoomController()
{
_room = new Room();
}
//edit using _room
}
Let's say we have some class CarsBase
public class CarsBase
{
public string DisplayName { get; set; }
}
Then we have some other class Toyota
public class Toyota : CarsBase
{
public EngineType EngineType { get; set; }
}
Then we are initializing our class instance by using object initializer like so:
var myVar = new Toyota()
{
// DisplayName = "", ← We could do this by our hands, but can it be done automatically?
EngineType = EngineType.UZ
}
Question: Is there any way to fill CarsBase's DisplayName property automatically on object initialize?
Like, if I had several more car classes (BMW, Suzuki , etc.), each is extending CarsBase and as a result have DisplayName property in each class.
This sounds like something that should be done in a constructor.
public class Toyota : CarsBase
{
public Toyota() : base()
{
base.DisplayName = "Toyota";
}
public EngineType EngineType { get; set; }
}
Another option, however less recommended, instead of getting/setting a DisplayName in the same sense, the base class could be changed to use reflection retrieve the classname and use that as the display name:
public class CarsBase
{
public string DisplayName
{
get
{
return this.GetType().Name;
}
}
}
This method should just return the "Toyota" from the classname, however would prevent usage of spaces or other special characters. Reflected code such as this also has a tendency to be slower.
Create a constructor to pass dispay name (or other parameters as required)-
Toyota(string displayName)
{
DisplayName = displayName;
EngineType = EngineType.UZ;
}
Then you can call like this-
new Toyota("some display name");
Just set the property value in the constructor. Something like this:
internal class Program
{
private static void Main(string[] args)
{
Toyota t = new Toyota() { EngineType = new EngineType() };
Console.WriteLine(t.DisplayName);
Console.ReadLine();
}
}
public class CarsBase
{
public string DisplayName { get; set; }
}
public class Toyota : CarsBase
{
public EngineType EngineType { get; set; }
public Toyota()
{
// set the default Display Name
// that way you don't have to set it everytime
this.DisplayName = "Oh what a feeling!";
}
}
public class EngineType { }
Yes, it can be done during the initialization stage of object where constructor is fired . I have created two classes
* one for holding enum constant value for engine_Types --> EngineType
one for explaining the inheritance,Constructor-Chaining, creating an instance of class which is an object----> CarsBase
[pre]
namespace stacketst
{
public class CarsBase
{
public string DisplayName { get; set; }
public CarsBase()
{
//called when CarBase object is initialized
DisplayName = "Base Car";
}
}
public class Toyota : CarsBase
{
//getters , setters called as properties in C#
public int number_of_wheels { get; set; }
public double fuel_capacity { get; set; }
public string engine_type { get; set; }
public Toyota() //called when an instance of Toyota is created
{
//assinging value to this property calls set
fuel_capacity = 4.2;
number_of_wheels = 4;
engine_type = EngineType.name_engines.UZ.ToString();
}
}
public class TestClass
{
static void Main()
{
//when below line is executed,constructor is fired & the initialization of variable inside constructor takes place
var myVar = new Toyota();
Console.WriteLine(myVar.DisplayName);
}
}
}
namespace stacketst
{
public class EngineType
{
//enums to hold constants, common for any Car Class
public enum name_engines
{
V12, V10, V8, V6, UZ
};
}
}
[/pre]
I want the following, is it possible in C#
public class BaseClass
{
public string Name {get;set;}
public DateTime Login {get;set;}
}
public class ChildA : BaseClass
{
public string SchoolName{get; set;}
public string ClassName{get; set;}
}
public class childB : BaseClass
{
public string StreetAdrees{get; set;}
}
Now I want that if I create an instance of any child class Name="John" and Login "2013-12-12" or from database already set its irritating to set these attribute for every class
just like that
ChildA obj=new ChildA();
obj.Name and obj.Login already have Data
Specify constructor in base class, then create constructors in child classes which inherit from base classes constuctor like below
public class ChildA : BaseClass
{
public ChildA():base(){}
public string SchoolName{get; set;}
public string ClassName{get; set;}
}
public class BaseClass
{
public BaseClass()
{
//set Data
.....
}
....
}
read more about base keyword
In the example below, children would actually point to the same instance of base
The example uses cache, but it could be anything else (session, application state, etc).
public class BaseClass
{
private string _name;
private DateTime _login;
public string Name
{
get
{
return Instance._name;
}
set
{
_name = value;
}
}
public DateTime Login
{
get
{
return Instance._login;
}
set
{
_login = value;
}
}
public static BaseClass Instance
{
get
{
// check if null, return a new instance if null etc...
return HttpContext.Current.Cache["BaseClassInstance"] as BaseClass;
}
set
{
HttpContext.Current.Cache.Insert("BaseClassInstance", value);
}
}
}
public class ChildA : BaseClass
{
public string SchoolName { get; set; }
public string ClassName { get; set; }
}
public class childB : BaseClass
{
public string StreetAdrees { get; set; }
}
testing it:
BaseClass.Instance = new BaseClass() { Login = DateTime.Now, Name = "Test" };
ChildA ch = new ChildA();
ChildA ch2 = new ChildA();
childB chb = new childB();
Response.Write(ch.Login.Millisecond);
Response.Write("<BR/>");
Response.Write(chb.Login.Millisecond);
Result:
906
906