Class Variables and Methods not Available to other class - c#

I am getting this problem. I created a class in a Windows Forms Application - WFA. It has one namespace as XmlParsing. it has two classes, both public, one partial. One class is named as myWindow; this is also public partial class. The other is MemberFunction class; this is public only. It has few strings and simple get n set methods. Now the issue is none of the variables and get n set methods are showing up in the myWindow class.
Please help. This is how I am doing stuff:
namespace XmlParsing
{
MemberFunction Class is here
myWindow Class is Here
}
Both are completely separate. I don't get where m running out of my limits.

Make sure your properties/variables are defined as public in your class. For example
class myWindow
{
public string MyProperty { get; set; }
public int Field1;
public static int StaticField;
}
Also if they are non-static members then you have to create an object of the class to access them.
myWindow objMyWindow = new myWindow();
objMyWindow.MyProperty = "Some string";
objMyWindow.Field1 = 10;
If you have defined a field as static you can access it against class name as well, like:
myWindow.StaticField = 100; //accessing static field
You may consider renaming your class and use Pascal case for class names.

Related

Static referenced in another .cs file

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);

In case i have class with only one static variable - should i declare this class as static?

This is my class how hold my last visited Path:
public class LastPath
{
private static string _lastPath;
public static string lastPath
{
get { return _lastPath; }
set { _lastPath = value; }
}
}
If all members of a class is static and your class is not meant to instantiated it should be static.
In this case your class satisfies the above rule or guideline so marking it as static will make sense because you don't have any instance member.
LastPath path = new LastPath();
path.????// Nothing to access, so prevent instantiation by marking class static.
Being said that If you have only one field in your class and no methods I'd argue that you probably don't need a class at all, just refactor it to some other class where it would make sense.
make the class static and make a public property as static and you are done, like this:
public static class LastPath
{
public static string lastPath { get;set;}
}
I would say you to do this:
public static class LastPath
{
public static string lastPath
{
get;set;
}
}
You should declare it as static as static classes cannot be instantiated, while non static classes can be instantiated, which is not needed.
First - it looks odd to me to create class for holding single variable. Consider to use simple string variable lastVisitedPath instead. If you use this variable in single class, then make it field of that class.
Second - naming is not very readable. Here is how getting last path looks like: LastPath.lastPath. You see this useless duplication? Also keep in mind, that due to Microsoft naming guidelines public members should have Pascal Case names. Consider to create class with descriptive name like GlobalValues or Cache which reflects its purpose:
public static class GlobalValues // holds values which are globally accessible
{
public static string LastVisitedPath;
// other global values
}
So that usage will look like GlobalValues.LastVisitedPath or Cache.LastVisitedPath. Of course, if these classes don't supposed to be instantiated, they should be static.

can't acess public static member of one class from another class

I am writing windows forms application which needs to have global variable to change from one Form class and then to be used from another Form class
this is class for global variables
namespace Testi
{
public class publicVar
{
public static int kitxvisN = 0;
public static int sworipas = 0;
}
}
and this is class where I want to use it
namespace Testi
{
public partial class Form1 : Form
{
publicVar something = new publicVar();
something.kitxvisN++;
....
but it says invalid token ++ . . .
what is wrong can somebody help me?
You're trying to access static member as if it was not static. You don't need, and even can't use class instance to access static members. Use class name instead:
publicVar.kitxvisN++;
Because there is no instance variable, you access the members of a
static class by using the class name itself.
from Static Classes and Static Class Members (C# Programming Guide)
Update
Other thing is, you can't use code like that directly on class level. You need some method to put it inside it.
public void MyMethod()
{
publicVar.kitxvisN++;
}
static members can't be used with objects. They can be accessed by class name such as publicVar.kitxvisN ++;
Simply try with:
publicVar.kitxvisN++;
Because it's a static member and which does not require an instance to access that. static member should simply be accessed by class name itself.
You can't place those methods directly under class declaration. It has to be inside of a method. E.g.
namespace Testi
{
public partial class Form1 : Form
{
public static void Main(string[] args) {
publicVar.kitxvisN++;
}

IntelliSense doesn't show partial class method

I have partial class User generated by LINQtoSQL as shortly following:
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.[User]")]
public partial class User : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
...
Then I created separate folder "Proxy" in my project and put there extra piece of User class:
namespace LINQtoSQL_sample.Proxy
{
public partial class User
{
public static string GetActivationUrl()
{
return Guid.NewGuid().ToString("N");
...
Issue happens when I try to invoke that extra static method from another part of same project. Let's say I have once more folder "SqlRepositoryImpl" and another one partial class there:
namespace LINQtoSQL_sample.SqlRepositoryImpl
{
public partial class SqlRepository
{
public bool CreateUser(User instance)
{
if (instance.ID == 0)
{
instance.added_date = DateTime.Now;
instance.activated_link = LINQtoSQL_sample.Proxy.User.GetActivationUrl();
...
As you can see I explicitly defined which part of User class I'm calling for because IntelliSense didn't suggest me my extra method.
Please, advise why such happens and where I'm wrong?
As you can see I explicitly defined which part of User class I'm calling for because IntelliSense didn't suggest me my extra method.
When you call a method from a class, there are no “parts” of the class anymore.
If you need to (and can) specify the full namespace of the class to invoke a method from it that means you actually have two different classes in two different namespaces. If the two partial declarations are in different namespaces, then you have actually declared two separate classes, not a single class from two parts.

Access variable from other namespaces

I am trying to set/read a variable in class bluRemote from another namespace/class like so:
namespace BluMote
{
class bluRemote
{
public string cableOrSat = "CABLE";
........
}
}
and the other cs file (which is the form):
namespace BluMote
{
public partial class SettingsForm : Form
{
if (BluMote.bluRemote.cableOrSat == "CABLE")
{
BluMote.bluRemote.cableOrSat = "SAT";
}
.......
}
}
I know i am doing it wrong but I'm more used to doing stuff like this in VB so its like night and day ha :o)
What you are trying to do is work with static variables so you would need to change your class to this:
namespace BluMote
{
public static class bluRemote
{
public static string cableOrSat = "CABLE";
........
}
}
It is better if you stay away from static classes (for the most part) and instead focus on an object oriented approach where you have an instance (object) of bluRemote.
So instead of making the bluRemote class static you keep it the same and do:
public partial class SettingsForm : Form
{
private bluRemote _remote = new bluRemote(); // possibly created somewhere else
public void SomeFunction()
{
if (_remote.cableOrSat == "CABLE")
{
_remote.cableOrSat = "SAT";
}
}
.......
}
You're trying to access an instance variable - i.e. one which has a potentially different value for each object - just by class name. That only works for static variables.
You need to have an instance of bluRemote, and ask that for its value. However, I would strongly suggest that:
You rename your class to follow .NET naming conventions
You don't make variables public; use properties
Also note that there's only one namespace here - BluMote. Both of your classes are declared in that namespace.
As you've declared the cableOrSat field, you'll need to set it on an instance of the bluRemote class, but you are trying to set it using the name of the class itself.
If you declare the cableOrSat field as:
public static string cableOrSat = "CABLE";
You will be able to access it through the class name itself.

Categories

Resources