Say i have
public int MyVariable;
in the Form1.cs file, and I want to access it from Class1.cs , what do you think would be the best way to do that?
Thanks!
MSDN: Properties
base class with property:
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
}
Auto Implemented Properties (if advanced work on "name" isn't needed):
class Person
{
public string Name { get; set; } // the Name property with hidden backing field
}
Class accessing the property:
Person person = new Person();
person.Name = "Joe"; // the set accessor is invoked here
System.Console.Write(person.Name); // the get accessor is invoked here
It depends on the scenario. But ideally, Form elements are passed to any functions that will need to use them.
You have a few options:
Pass the value to the class/method that's using it. This is the preferred scenario. If your class depends on this value, supply the value to the class. Don't make the class go looking for it. (See: Dependency Inversion Principle)
Make the value static. Then any other class can refer to that value. Note the difference between instance and static, of course. The value will always be the same and needs to be given in the definition of the member, not in a constructor or other logic.
Create an instance of the form (which is itself just a class) within the class and access the public member on that instance. This is unlikely to be what you want because the instance you're creating isn't the instance that's running "on the page." (It also violates the principle noted above.)
Pass a reference to the form (this) to the class and refer to the member from that reference.
On a side note, you'll want to get in the habit of making your public members properties instead of variables. In most cases, the property will likely just get/set the variable and nothing more. However, if something more ever needs to be added it can be done so without breaking compatibility. Changing a variable to a property changes the footprint of the class and breaks things which use that class.
Make the variable static. Then you can call it like Form1.MyVariable.
Try like this:
In case (1) you can have MyClass.MyInt private readonly.
public class MyForm : System.Windows.Forms.Form
{
int myInt;
public MyForm()
{
myInt = 1;
//1
var myClass = new MyClass(myInt);
//2
myClass.MyInt = myInt;
}
}
public class MyClass
{
public int MyInt { get; set; }
public MyClass(int myInt)
{
MyInt = myInt;
}
}
Related
I am overlooking something simple I think. I have a form with a checkbox. I need to know if the checkbox is checked in a different cs file/class to know whether to make a column header Option1 or Option2.
Form1 (Public partial class) code:
public bool Checked
{
get
{
return checkBox1.Checked;
}
}
In my Export1 class I have private void CreateCell1 that takes in the data to be exported (creating an excel file from a datatable). The section of code I can't get to work is:
if (Form1.Checked.Equals("true"))
{
newRow["Option1"] = date2;
}
else
{
newRow["Option2"] = date2;
}
I am getting -Error 1 An object reference is required for the non-static field, method, or property 'Matrix1.Form1.Checked.get'
What did I overlook?
Well, the problem here is exactly what the compiler is telling you. You need an object reference in order to access the property.
Allow me to explain.
In C#, by default, class members (fields, methods, properties, etc) are instance members. This means that they are tied to the instance of the class they are a part of. This enables behavior like the following:
public class Dog
{
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
var dog1 = new Dog { Age: 3 };
var dog2 = new Dog { Age: 5 };
}
}
The two instances of Dog both have the property Age, however the value is tied to that instance of Dog, meaning that they can be different for each one.
In C#, as with a lot of other languages, there are things called static members of classes. When a class member is declared static, then that member is no longer tied to an instance of the class it is a part of. This means that I can do something like the following:
public class Foo
{
public static string bar = "bar";
}
public class Program
{
public static void Main()
{
Console.WriteLine(Foo.bar);
}
}
The bar field of the Foo class is declared static. This means that it is the same for all instances of Foo. In fact, we don't even have to initialize a new instance of Foo to access it.
The problem you are facing here is that, while Form1 is not a static class and Checked is not a static property, you are treating it as such. In order for what you are trying to do to work, you need to create an instance of Form1 and access that instance's Checked property.
Depending on how your program is structured, there are many ways of doing this. If Form1 is created in the scope where you are trying to access Checked, then this will be straightforward. If Form1 is what spawns the new scope, then common practice is to pass a reference to it in the constructor.
For example, if Form1 creates a new Form2 then we do the following:
public class Form2 : Form
{
private Form1 parent;
public Form2(Form1 parent)
{
this.parent = parent;
InitializeComponent();
}
}
And then you can access parent throughout Form2. Of course, depending on the structure of your program, the exact implementation will be different. However, the general pattern is the same. Pass the reference to Form1, from the scope it was created in, to the new class, and then access it from there.
One way or another, you need to access the specific instance of Form1 that you're trying to check.
A few ways to do this are:
Pass the instance to the class constructor
Setting a public property of the other class to the instance of the form
Pass the instance to the method directly
For example:
public class SomeOtherClass
{
// One option is to have a public property that can be set
public Form1 FormInstance { get; set; }
// Another option is to have it set in a constructor
public SomeOtherClass(Form1 form1)
{
this.FormInstance = form1;
}
// A third option would be to pass it directly to the method
public void AMethodThatChecksForm1(Form1 form1)
{
if (form1 != null && form1.Checked)
{
// Do something if the checkbox is checked
}
}
// This method uses the local instance of the Form1
// that was either set directly or from the constructor
public void AMethodThatChecksForm1()
{
AMethodThatChecksForm1(this.FormInstance);
}
}
This class would need to be instantiated by the instance form1 using one of these methods:
// Pass the instance through the constructor
var someOtherClass = new SomeOtherClass(this);
// Or set the value of a property to this instance
someOtherClass.FormInstance = this;
// Or pass this instance to a method of the class
someOtherClass.AMethodThatChecksForm1(this);
Let's say I have a class called TestClass. I want the application to contain only one instance of this class at a time.
I have a heritable class name Singleton, I use it like this :
public class TestClass : Singleton<TestClass>
{
}
And I use it like this
TestClass.Instance // Gives me one instance
The thing is, from time to time, I'll need to re-instantiate the TestClass often, with new parameters etc..
Should I make a static instance and just re-instantiate whenever I want, or is there a better way to do this?
Thanks and sorry.
Singleton is meant to be existing until the app is terminated and shouldn't be re-instanitated. If you want to change any member of this class, create setter method.
For instance, if you have a singleton class and two members in it:
public int Integer1 { get; private set;}
public string String1 { get; private set;}
You can either create two setters or, if these two properties should be changed together, create one method which will set them a given values:
public void SetIntAndString(int int1, string str1)
{
Integer1 = int1;
String1 = str1;
}
There should never exist any way to delete or modify the class instance object itself.
Suppose you have the following A class definition:
class A
{
protected double[] _temperatures;
double[] Temperature
{
get {return _temperatures;}
set {_temperatures = value;}
}
}
How should I access temperatures in a derived class B? Using the member field or the property? Should I declare _temperatures as private and always use the property? What is the overhead of using the property instead of direct member field access?
Thanks.
You should use the property and make the field private. But your code with a custom private field only make sense if you really need to add some custom logic in the getter or setter. So for your simple case, you can go with this:
class A
{
protected double[] Temperature { get; set; }
}
Yes change the data member to private. Using a Property instead of a Field (private member) is a better way of accessing it even if its from within the same class so that if you have some logic in the getter/setter you don't have to repeat it each time you set the value.
Even if you don't have logic its better to use property as you might need to add some logic in future. It will be a single point of entry for getting and setting the value.
And yes as Kevin suggested you can use auto-implemented property if you don't have custom logic.
You may modify your code like this:
class A
{
private double[] _temperatures;
public double[] Temperature
{
get { return _temperatures; }
set { _temperatures = value; }
}
}
class B : A
{
public B()
{
B b = new B();
Console.WriteLine(b.Temperature);
}
}
Local variable '_temperatures' should be private and property 'Temperature' should be either public or protected.
Ideally a class should not expose its members (in your case _temperatures) to the outside world. Members are meant to be used internally with in a class. If you want to expose a class member then use properties. Thats ideal way of designing a class.
The advantage of this type of class designing is tomorrow suppose there is a need to add some logic when assigning a value or retrieving a value from a class member then it can be easily accomodated with in a property without redesigning the interface.
So declare _temperatures as private and expose it to derived classes by declaring the property Temperature as protected.
Refer this C# tutorial for additonal information:
I am reading Beginning Visual C# 2012.
Consider:
using System;
using System.Collections.Generic;
using System.Text;
namespace Ch10Ex01
{
class MyClass
{
public readonly string Name;
private int intVal;
public int Val
{
get { return intVal; }
set
{
if (0 <= value && value <= 10)
intVal = value;
else
throw (new ArgumentOutOfRangeException("Val", value,
"Val must be assigned a value between 0 and 10."));
}
}
public override string ToString()
{
return "Name: " + Name + "\nVal: " + Val;
}
private MyClass() : this("Default Name")
{
}
public MyClass(string newName)
{
Name = newName;
intVal = 0;
}
}
}
Explanation in the book: Note that I've used this ("Default Name") to ensure that Name gets a value if this constructor ever gets called, which is possible if this class is used to derive a new class. This is necessary as not assigning a value to the Name field could be a source of errors later.
What's puzzling me: How can it be used in a derived class as it's "private"? What does this ("Default Name") mean? How does the object get the "Default Name" as its name?
What's puzzling me: How can it be used in a derived class as it's "private"? What does this("Default Name") mean? **How does the object get the "Default Name" as its name?
You are right to be puzzled!
That code sample does not call the default constructor at all - and because it is private, nothing else can call it without using reflection (not even a derived class; it would have to be at least protected for a derived class to call it - or the derived class would have to be nested within the base class).
In the sample code, the object does not get "Default Name" as its value.
So it's a typo or an error in the book.
The correct solution to what the book is describing is to:
Omit the default constructor altogether.
Initialise Name at field scope. This ensures that it is impossible to fail to initialise it, no matter what other constructors are written in this or any derived class.
Like so:
class MyClass
{
public readonly string Name = "Default Name";
private int intVal;
public int Val
{
get
{
return intVal;
}
set
{
if (0 <= value && value <= 10)
intVal = value;
else
throw (new ArgumentOutOfRangeException("Val", value,
"Val must be assigned a value between 0 and 10."));
}
}
public override string ToString()
{
return "Name: " + Name + "\nVal: " + Val;
}
public MyClass(string newName)
{
Name = newName;
intVal = 0;
}
}
Note that it can often be useful to declare a private default constructor which is called by other constructors - but the declaring class has to actually use it.
Also note that if you declare a non-default constructor in a base class and do not declare a default constructor at all, any derived class must call one of the existing base class constructors.
For example given the class definition above, then both the following class declarations will cause a compile error MyClass' does not contain a constructor that takes 0 arguments:
class MyDerivedClass1: MyClass
{
public MyDerivedClass1() // Compile error
{
}
}
class MyDerivedClass2: MyClass
{
// No constructor declared at all. Also a compile error.
}
To fix the error, MyDerivedClass has to call an existing constructor:
class MyDerivedClass: MyClass
{
public MyDerivedClass(): base("My new name")
{
}
}
So what use is a private constructor
A fairly typical use is to put common initialisation code into a default constructor. Sometimes, however, you don't want the caller to be able to default-construct the type - in which case you can make the default constructor private.
That way, you can still use the default constructor for common initialisation but you prevent code outside the class from doing it, for example:
class Test
{
public readonly int IntValue;
public readonly string StringValue;
private Test()
{
// Do common initialisation.
}
public Test(int intValue): this()
{
IntValue = intValue;
}
public Test(string stringValue): this()
{
StringValue = stringValue;
}
}
Often you could just use a private init() method to do the common initialisation, but if you are initialising a readonly field you must use a constructor to do so. In that case, a private constructor must be used instead of an init() method.
Another use of a private default constructor is to prevent any instantiation of the type at all (you just declare a private default constructor and no other constructors at all).
In .Net 1.x that was the only way to do so - but subsequent versions of .Net introduced static classes which for most cases removed the need to use a private constructor for that type.
You might also declare a private constructor to force the use of a static factory method to instantiate the type.
Just for completeness, here's a contrived example that demonstrates how a private constructor can be called from a nested derived class:
class OuterClass
{
public readonly string Value;
private OuterClass(): this("Default Value")
{
}
public OuterClass(string value)
{
Value = value;
}
public OuterClass GetInnerClass()
{
return new InnerClass();
}
private class InnerClass: OuterClass
{
}
}
With that class definition, the following code will print "Default Value":
OuterClass test = new OuterClass("Test");
Console.WriteLine(test.GetInnerClass().Value);
Personally I've never had to write a nested class that derives from its containing class, but it's possible if you need to do it for some reason.
Because this class has a private constructor, the ONLY way that the constructor can be called is within this particular class. Not even a derived class can call it (if it was protected then it could). As your code example shows, this serves no purpose.
The reason why it's a default constructor calling another is just a way of having a hard-coded default value without the user knowing/caring what it is. This is similar to default parameters for functions in .NET 4.0.
To me, it would make much more sense to make both constructors public, because I don't see any code that uses the default constructor (if you have shown us all the code).
There are some legitimate reasons to use private constructors, specifically with static functions or sub-classes. Take the following for example:
public class OuterClass
{
private OuterClass() { }
public static OuterClass GetOuter() { return new OuterClass(); }
}
In this way, you can only make a new instance of the class from the static method.
A private constructor means a user can not directly instantiate a class. Instead, you can create objects using something like the named constructor Idiom, where you have static class functions that can create and return instances of a class. You can use the private constructor to control the instantion of the Object usually used in the singleton pattern.
You have to read the singleton pattern to understand the purpose of the private constructor.
interface IAnimal
{
string Name { get; set; }
}
class Dog : IAnimal
{
private string name;
public Dog(string name)
{
Name = name;
}
public string Name
{
get { return name; }
set { name = value; }
}
}
In general, it's better to go through the property getter and setter whenever possible unless there is a specific reason not to. If the property setter has a side effect (like firing a notification) that you don't want in a specific situation, it's ok to assign to the backing field directly from within the object, but try to avoid getting into that sort of situation.
The reason it's good to use the property getter and setter, even in the implementing class itself: when/if you need to change the implementation of the getter/setter in the future, such as adding needed side effects, your code will already be in a good position to honor the new getter/setter semantics.