Calling a non-static Variable from another Class - c#

I want to call non-static variable from another class. If I make it static, it affects my other code.
I've two classes Harvest_Client and Harvest_Project.
In my Harvest_Project class I've
public int _client_id{ get; set;}
I'just want to do in Harvest_Client class is,
public int _id = Harvest_Project._client_id;
How should I do this?

Firstly, you should rename the property (it's not a variable) to conform with .NET naming conventions, e.g.
public int ClientId { get; set; }
Next, you need an instance of HarvestProject (post-renaming). Don't just create a new one - you need the right instance, the one whose client ID you're interested in. We can't tell you which one it is - but if you don't already have an instance of HarvestProject to hand, you should work out how you're expecting to specify which client ID you want.
Think of it this way: if I were to ask you "How old is a person?" you'd naturally want to know which person I was talking about. It's exactly the same here.

maybe passing the reference to the class will do what you need:
public class Harvest_Project
{
public string Name { get; set; }
public int clientId { get; set; }
}
public class Harvest_Client
{
private Harvest_Project MyInstance;
private int myid;
public int MyId
{
get
{
return myid;
}
private set
{
MyId = value;
}
}
public Harvest_Client(Harvest_Project cls)
{
MyInstance = cls;
MyId = cls.clientId;//since class reference present no
//need for the property.
//its just here to show if in your
//project you really just need ID
//in this example its redundant
}
}
Depending on what you are trying to do you can make a List of Harvest_Project objects or better a dictionary,if there are various types of "projects" they could be all placed in a dictionary cataloged accordingly to the specified key.

One moment I would like to recommend to take into consideration the following declaration of property public int ClientId {get; private set;"} It allow you to prohibited setting this variable from third party code, if you actually need this. Otherwise you will have ordinary global variable

Related

What is a good design pattern to avoid having to use a global variable at the top your main form?

Every time I talk to experienced programmers, they talk about having global variables being a bad practice because of debugging or security exploits. I have a simple List of strings I want to load from a a textfile and access across different methods in my form. Before, I would simply initialize said variable at the top, inside of my form class and use it across methods. I always try to reduce that practice when I can and only initialize those variables when I really need them. Is it a bad practice to do this or do more experienced programmers do this too? Is there a standard design pattern method of doing this so you don't have to use "global variables" at the top of your form?
As you're talking about C# and it's a fully-object-oriented programming language, there's no way to declare global variables.
In an OOP language like C#, a bad practice can be simulating global variables using static classes:
public static class Global
{
public static string Value1 { get; set; }
public static int Value2 { get; set; }
}
...to later get or set these values from other classes. Definitely, this a bad practice because state should be held by specific and meaningful objects.
Usually, in a perfect/ideal OOP solution, you should pass such values from class to class using constructors:
public class X
{
public int Value1 { get; set; }
public void DoStuff()
{
Y y = new Y(this);
y.DoChildStuff();
}
}
public class Y
{
public class Y(X parent)
{
Parent = parent;
}
public X Parent { get; }
public void DoChildStuff()
{
// Do some stuff with Parent
}
}
Or also, you might pass states providing arguments to some method:
public class Y
{
public void DoChildStuff(X parent)
{
// Do some stuff with "parent"
}
}
Since you're passing states with reference types, if any of the methods in the chain decide to change Parent.Value1 with another value, all objects holding a reference to the same X object will get the new X.Value1.
Some fellows might argue that we usually build configuration objects which own a lot of properties accessed by other arbitrary objects, right? BTW, configuration is a concept per se, isn't it? And we usually categorize configuration values using composition:
public class ApplicationConfiguration
{
public DatabaseConfiguration Database { get; } = new DatabaseConfiguration();
public StorageConfiguration Storage { get; } = new StorageConfiguration();
}
public class DatabaseConfiguration
{
public string ConnectionString { get; set; }
}
public class StorageConfiguration
{
public string TemporalFileDirectoryPath { get; set; }
public string BinaryDirectoryPath { get; set; }
}
So later we inject the application configuration wherever we need it:
// Please note that it's a VERY hypothetical example, don't take
// it as an actual advise on how to implement a data mapper!!
public class DataMapper
{
public DataMapper(ApplicationConfiguration appConfig)
{
AppConfig = appConfig;
}
public ApplicationConfiguration AppConfig { get; }
private IDbConnection Connection { get; }
public void Connect()
{
// We access the configured connection string
// from the application configuration object
Connection = new SqlConnection(AppConfig.Database.ConnectionString);
Connection.Open();
}
}
In summary, and since I love comparing real-world and programming use cases, imagine that you never clean your room and you would use a single box to store every tool you might need some day. One day you need a screwdriver from the whole box, and you know that's inside it... But you need to throw everything in the box to the ground and work out the mess prior to find the priceless screwdriver to complete some home task.
Or imagine that you've bought a toolbox to store your tools in order, and once you need a screwdriver, you know that's in the toolbox and in the section where you store your screwdrivers.
You know that the second approach is the most mind-friendly. That is, when you develop software, you need to design mind-friendly architectures rather than a big mess of unrelated data and behaviors working together.

How to pass parameter to class C#?

I have code as below
public class LocalDB
{
public static int e_SessionID;
public static string e_EventName;
public static string e_TimeCreate;
}
in other class:
public static LocalDB newEvent ;
public void something()
{
newEvent.e_SessionID=123;
}
but it is can not pass value.
Problem : You are trying to access the static feilds using instance reference variable newEvent as below:
newEvent.e_SessionID=123;
//^^^Here
Solution : You need to use classname to access the static fields
newEvent.e_SessionID=123;
//^^^Replace with classname LocalDB here
Replace this:
newEvent.e_SessionID = 123;
With this:
LocalDB.e_SessionID = 123;
Why don't you set them up as properties? Have a read of this SO post why prefer properties to public variables
"Fields are considered implementation details of classes and exposing them publicly breaks encapsulation."
public class LocalDB
{
public int SessionID { get; set; }
}
Static methods and variables can only invoke using the class name
and you are trying to call using the class object.
if you want to set the value of e_SessionID set the value using class name as follows
LocalDB.e_SessionID=123;
try to use property instead:
public class LocalDB
{
public int e_SessionID { get; set; }
public string e_EventName { get; set; }
public string e_TimeCreate { get; set; }
}
Prefer instance data to static data.
Static data is effectively global state. Do you have only one event in the lifetime of your program? What if you need to support multithreading? This is object-oriented programming; use objects.
Encapsulate data.
Avoid making fields public. Prefer properties, as others have stated. Note that this allows assigning the creation time at construction (and only then).
Use appropriate types.
If you are storing a date/time value, normally you would use the DateTime class.
Favor immutability.
If you know the values of properties at construction time, set them then and don't allow them to be changed.
Think about names.
Descriptive names matter, especially when you're doing maintenance after six months. I didn't change the name of LocalDB in my example, as I don't know your domain or use case. However, this class looks more like an event than a database to me. Would Event be a better name?
The following example uses C# 6 syntax; earlier versions would need to add private setters and move the initialization to the constructor.
public class LocalDB
{
public LocalDB(int sessionID, string eventName)
{
SessionID = sessionID;
EventName = eventName;
}
public int SessionID { get; }
public string EventName { get; }
public DateTime TimeCreate { get; } = DateTime.UtcNow;
}
public class Other
{
public void DoSomething()
{
NewEvent = new LocalDB(1, "Other Event");
}
public LocalDB NewEvent { get; private set; }
}
A flaw in this example is that the NewEvent property of an Other instance will be null on creation. Avoid nulls where possible. Perhaps this should be a collection of events; not knowing your use case I can't say.

property: private method or private get/set?

If I want to set my property in a Class private, so it should be only possible to use and set this property in this class, what is the better way? This
public string Name { private get; private set }
or
private string Name { get; set }
hmmm and there is also
private string Name { private get; private set }
It's worth noting that originally, C# wouldn't let you set different accesses on a getter or setter, so the only possible choices were:
public string Name { get; set; }
protected internal string Name { get; set; }
internal string Name { get; set; }
protected string Name { get; set; }
private string Name { get; set; }
(For that matter, you couldn't have automatic properties and always had to do the writing to and from a backing field yourself, but we'll ignore that just because we'll have shorter examples that way).
It is often useful to have different accesses for the two, most often a more restrictive setter than getter, and so the likes of
public string Name { get; private set; }
was introduced.
Now, by extension of that, it would seem logical enough to allow:
public string Name { private get; private set; }
private string Name { private get; private set; }
However, what are these two expressing?
The second isn't too bad, it's just needlessly repetitious. Still though, it's quite likely that some confused thinking got us there (most likely an incomplete refactoring). Good code is as much about expressing what you are doing as making a computer do something (if anything, more so), better to have it express clearly.
Hence if you end up with the likes of { private get; private set; } then it'd likely be worth looking at again and thinking about what you really want to say here. Hurrah for it being a compiler error.
The first case is even worse. It says "this property is public, except for the setter that is private, and the getter that is private". That's not an exception, "it's this thing, except for all the time" is no real expression of anything. Doubly hurrah the compiler for not letting us do it.
Have you tried compiling your examples? Only the middle one will translate.
If you want to specify extra accessibility level keyword, you can only do it on one of the accessors (getter/setter), and that level of the accessor must be more restrictive than the accessibility of the entire property.
Here you see the rules: Restricting Accessor Accessibility
public string Name { get; private set; }
This is what I think you are wanting to do.
There is no point trying to make the get private when the property is public unless you only want your class to see it. In that situation you should use:
private string Name { get; set; }
Update: On second read, you definitely want the second example.
The better way depends on what you want:
public string Name { private get; private set } The property is public but noone can read or wrote to it, except class itself. That is completely useless, so use just
private string Name { get; set }.
In general if you view the property like a couple of methods (which actually is)
private string get_Name() { }
private string set_Name(value) { }
The reason of having a possibility to apply that identifiers to a property get/set becomes evident, I hope.
For a private member, you don't need to define accessors.
Just do this:
private string _name;
It seems like you want
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
this would allow you to access private string Name.
surely enough,
That is the definition of private classifier in OOP: just allow access within methods and scope of the class that owns such private member. Thus if your aim is to disable anyother means of access to a particular member of a class, claiming it as:
private <Type_name> <member_identifier> ;
is the simplest and enough to make it such.

C#, accessing a variable from a class?

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

Should I declare my abstract class's attributes with get; set;?

I'm making a little program that will crawl my hard drive and present a list of file found in a given drive.
My idea is to have a base File class, and implement Picture.cs, Video.cs and Document.cs classes inherited from the File.cs class.
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharpLibrary_MediaManager
{
public abstract class File
{
public string name;
public string fileType;
public int size;
public DateTime creationDate;
public DateTime modificationDate;
}
}
Should I declare the short hand code for each attribute like this:
public string name { get; set; }
Any guidance will be helpful. Thank you. :)
Edit:
I mean literally replacing this line:
public string name;
with this line:
public string name { get; set; }
First, "attributes" is not the correct terminolgy here. When you declare a member of a class that has get and/or set defined (formally known as "accessors"), you are defining a property. Properties are a convenient way to expose values of private fields because you can add logic to the getting and setting mechanims.
Second, when you declare a member name as you've done via
public string name { get; set; }
the compiler will expand that into the following:
private string _name;
public string name {
get {
return _name;
}
set {
_name = value;
}
}
That is, the compiler will automatically create a backing field for you and define the accessors. These are called "automatic properties" (for the people)1.
Third, you should never2 publically expose fields. So, if you want to expose the string name as part of your public interface it is better to do it as a property. First, it provides better encapsulation. Second, it can be declared virtual and overridden in dervied classes. Third, you can have custom logic. Fourth, you can have different levels of accessibly between the reading and writing mechanisms on properties but you can not on a field.
Fourth, per accepted naming convetions, public properties should be named with CamelCase so that you should prefer Name instead of name.
1: Sorry, bad joke that I've been waiting a long time to make.
2: Almost never.
You're not describing a short hand syntax for a single item but rather 2 completely different types of members. The get/set version creates a C# Property while the non-get/set version creates a field.
// field
public string name;
// property
public string name {get; set;}
So what you're actually asking here is whether or not you should expose name as a field or a property. The answer is almost certainly property.
If your looking to have these properties, which is what adding the { get; set; } will make the variables, then you should declare the set; part of the property as protected.
So it becomes:
public string name { get; protected set; }
The advantage of this is that you are guaranteeing that the property can only be set by either the base class, or any class that inherits the base class.
As others have suggested, following the C# naming conventions is a good idea and also using properties are highly recommended.
Just to be clear, attributes are means to do declarative programming. They are used to decorate methods, classes, etc. msdn link
If you're asking whether to expose properties rather than public fields, then the answer is Yes.
You should also use PascalCase for the property names rather than camelCase:
public string Name { get; set; }
public string FileType { get; set; }
// etc
As Luke says, all things being equal, properties are preferred to fields.
In addition you may want to change the casing of your fields to match standard C# naming conventions.
Lastly, you might want to avoid the "File" name for your class as you'll probably be using the System.IO namespace which also has a File class. Also, System.IO.FileInfo may already include many of the properties you are planning on creating -- there's no point reinventing the wheel.
I believe another advantage of properties over normal public fields will be ability to override them in the derived class.
class Base
{
public virtual int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
public override int X
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}
Another useful trick that is applicable while using properties is the ability to modify the modifier of the the derived Properties like changing from Public access to Protected.
Hence in many ways its better to use properties in base class to derive.

Categories

Resources