I have recently start to practice c# and come across this problem:
I just want to save 'dataTaken' in 'public string date', so i can acces this variable directly.
class Bild
{
public int id;
public String source;
public string dataTaken;
public string data;
private string getAufnahmeDatum () {
string dataTaken = [.....]this.source;
return dataTaken;
}
**//-> data = this.getAufnahmeDatum(); // dose not work.**
}
I get some erros, trying this.
date : 'date' dose not exist in the current context
getAufnahmeDatum:
Method must have an return type
Bild.getAufnahmeDatum must declare a
body because its not marked abstarct,extern or partial
Type Bild already defines a memeber called getAufnahmeDatum with the same
parameter typs
I find it curios that when I dont define public string dataTaken; i get an error too ( dose not exist in th current context).
I thought string dateTaken = [...] should be enough.
PS: Is there a trick to copy that damn erros out of VisualStudio ?
You get exactly these error messages if you write this code inside the class but not within a method!
// fails with the described error
data = this.getAufnahmeDatum();
// works without error
private void Test()
{
data = this.getAufnahmeDatum();
}
You could for example call the code in the constructor of the class
public Bild()
{
data = this.getAufnahmeDatum();
}
This can be done in other way too by using set.
class Bild
{
public int id;
public String source;
public string dataTaken;
public string data
{
set { value = this.getAufnahmeDatum(); }
}
private string getAufnahmeDatum()
{
string dataTaken = this.source;
return dataTaken;
}
}
You can have get property also, if you want data to be read/write.
Related
I am a bit confused with the get set property in C#.
I have the simple code below:
using System;
class Example
{
int _number;
public int Number
{
get
{
return this._number;
}
set
{
this._number = value;
}
}
}
class Program
{
static void Main()
{
Example example = new Example();
example.Number = 5; // set { }
Console.WriteLine(example.Number); // get { }
}
}
The code above using get set properties. However, if I delete the get set code like below code, the results stay the same.
using System;
class Example
{
int _number;
public int Number;
{
}
}
class Program
{
static void Main()
{
Example example = new Example();
example.Number = 5; // set { }
Console.WriteLine(example.Number); // get { }
}
}
My query is, what is the get set code used for? In the above program, the results are same. Can you give me some simple code which show the get set usage?
In your code, Number is simply a public field, as evidenced by the semicolon (;) at the end.
public int Number;
It is not a property, you just have an empty set of brackets right underneath which led to your confusion. If you were to remove the ; then you would actually have a property that is missing it's get, and would not compile at all.
All properties need to have a getter (setters are optional). If you want to avoid writing them, you can use auto properties, which take care of the backing field without you having to get involved:
public int Number { get; set; } // No field required
Note: A common usage pattern you'll see involving auto properties is the following:
public int Number { get; private set; }
This allows for properties that can be read from anywhere, but can only be modified from within the class they belong to.
EDIT: To answer your question, the main difference between fields and properties is in encapsulation. You can read more about the general differences between fields and properties here.
However, the example you have given has one additional difference, the private set. A normal field can be written from and to throughout the program. A property with a private setter however can only be modified from inside the class it belongs to.
Example:
public class Foo
{
public int Id { get; private set; }
public string Name;
public Foo()
{
this.Id = 1; // This works!
}
}
Here, Name is a field and Id is a property with a private setter. Notice that we modify Id in the constructor and that works, because it is within the class Id belongs to. Moving outside the class however:
var foo = new Foo();
// Field (no get and set):
foo.Name = "test" // Works
string bar = foo.Name; // Works
// Property (get and *private* set)
int i = foo.Id; // Works, because get is public
foo.Id = 2; // Doesn't work, because set is private
I'd like to use the following C#6 code
var joe = new Self();
Console.WriteLine(joe);
... and get the following output:
joe
The following attempt
class Self {
public string Name { get; set; } = nameof(this);
public override string ToString() {
return Name;
}
}
fails as nameof cannot be applied to this. Is it there a workaround for this problem?
EDIT. The scenario I'm working with assures that no two references point to the same Self object.
No, nameof is designed to refer to the compile-time name of the member you're referring to. If you want an object to have a Name property as part of its state, that is independent of how you get to the Name property - as Frédéric Hamidi says, there could be multiple variables (or none) referring to the same object. Basically you need to differentiate between an object and a variable which happens to refer to that object.
However, if you have a constructor to specify the name, you could then use a couple of tricks to make it easier to get the right name:
class Self
{
public string Name { get; }
public Self([CallerMemberName] string name = null)
{
this.Name = name;
}
}
Then:
class Foo
{
private Self me = new Self(); // Equivalent to new Self("me")
public void SomeMethod()
{
// Can't use the default here, as it would be "SomeMethod".
// But we can use nameof...
var joe = new Self(nameof(joe));
}
}
Maybe you can use the following method:
class Self
{
public override string ToString()
{
return this.GetType().Name;
}
}
You can simply use nameof on the variable itself:
Console.WriteLine(nameof(joe));
Here's a working example using the current Roslyn version
The idea for nameof is to make things type safe for specifying program elements during runtime but with compile time type safety checking.
One should atomize what one wants to display. For example in my error messages I include the pertinent information of the class name and the method as such and its checked, so if I change any of the names they are caught as a compile time error:
class Operation
{
public void Execute()
{
try { ... }
catch (Exception ex)
{
Console.Writeline($"{nameof(Operation)}.{nameof(Execute)} has encountered exception:{Environment.NewLine}{Environment.NewLine}{ex.Message}" );
}
}
}
Output
Operation.Excecute has exception:
...
With that said you should override ToString() and report the class name as such
public override string ToString() { return nameof(Self); }
I usually create an internal constant for it when dealing with long class names:
private const string SomeConst = nameof(Self);
Then you can use that in your code:
Console.WriteLine(SomeConst);
I'm building a WinForms application using C# 2.0 for a Job Scheduler.
Wrote a public class Job in Program.cs defining the Job object.
//Class for defining Job object and its properties
public class Job
{
private int IntJobID;
public int JobID
{
get {return IntJobID;}
set {IntJobID = value;}
}
private string StrJobName;
public string JobName
{
get { return StrJobName; }
set { StrJobName = value; }
}
//Several other properties defined here.
}
Also wrote a public static class ApplicationName in Program.cs for containing application-wide config variables and all helper methods.
//Static Class for Global Properties and Global Methods
//*****************************************************
public static class ApplicationName
{
//Global Properties
//***************************
public static string ConfigFilePath = "D:\\ApplicationName\\conf\\ApplicationName.ini";
public static string DBFilePath = "D:\\ApplicationName\\data\\ApplicationName.xml";
//Global Methods
//************************
public static void HelperMethod1(Args)
{
}
public static string HelperMethod2(Args)
{
}
public static Job GetJobByID(int JobID)
{
XmlDocument XMLDB = new XmlDocument(); XMLDB.Load(DBFilePath);
Job ObjJob = new Job();
ObjJob.JobName = XMLDB.SelectSingleNode("/ApplicationName/Job[JobID=" + JobID.ToString() + "]/JobName").InnerText.Trim();
//Several other properties are retrieved from the DB and set to the object here.
return ObjJob;
}
}
One of the helper methods GetJobByID in the public static class ApplicationName is required to create/instantiate a Job object and return the same. I believe this is possible, a method within ClassA creating and returning an instance/object of ClassB.
Note: This method is meant for access from other forms such as Form1.cs, Form2.cs, etc. in the following way. To my knowledge, this is also allowed and is accepted practice.
private void FormAddEditJob_Load(object sender, EventArgs e)
{
int SelectedJobID = Convert.ToInt32(this.Tag);
//Creating an instance of the Job Class
//Assigning the value of the Job object returned by GetJobByID method
Job JobToEdit = ApplicationName.GetJobByID(SelectedJobID);
TextBoxJobID.Text = SelectedJobID.ToString();
TextBoxJobName.Text = JobToEdit.JobName;
}
PROBLEM: The object returned by GetJobByID method is not getting stored in the object reference JobToEdit. Or even possible that the GetJobByID method does not return an object appropriately / as expected. What am I doing wrong here? Is this not the right way to return an object?
Issue identified and resolved.
One of the statements ObjJob.PropertyName = XMLDB.SelectSingleNode() in the GetJobByID method was throwing an exception, due to fetching null values from the DB, thereby resulting in the ObjJob object being returned as null. Found this by debugging line by line.
i am returning a list from a database like this;
ClsCampus campus = new ClsCampus();
List<ClsCampus> camp = campus.GetCampusAll();
Utility.BindComboBox(ComboBoxCampus, camp, "CampusName", "CampusId");
I have a class name Utillity, in which i have created a static method called BindComboBox.
public static void BindComboBox(DropDownList listName, List<Object> list,
string textField, string valueField)
{
listName.DataTextField = textField;
listName.DataValueField = valueField;
listName.DataSource = list;
listName.DataBind();
}
However, it gives me a compilation error.
So, How do i write a general purpose method where i can bind a generic list of records to a combobox
Error 1
The best overloaded method match for 'KenMISSchool.Repository.Utility.BindComboBox(System.Web.UI.WebControls.DropDownList, System.Collections.Generic.List<object>, string, string)' has some invalid arguments D:\Projects\KenMISSchool\Web\forms\student\registration.aspx.cs 20 9 Web
You are passing List<ClsCampus> but method expects List<Object> so I would change it to generic way:
public static void BindComboBox<T>(DropDownList listName, List<T> list, string textField, string valueField)
{
listName.DataTextField = textField;
listName.DataValueField = valueField;
listName.DataSource = list;
listName.DataBind();
}
and call it like this:
Utility.BindComboBox<ClsCampus>(ComboBoxCampus, camp, "CampusName", "CampusId");
We had a similar idea, but solved it in another way. I'm not sure if it will work for you, but here's a suggestion:
We implemented an Interface called IDropdownable (not the best name, I know), that forced two properties:
public string dropdown_value;
public string dropdown_text;
And we then implemented this interface over all classes that needed to be easily bound to dropdownlists:
public class Foo : IDropdownable
{
//Let's say these fields are already in the class:
private int _id;
private string _name;
private DateTime _date;
//The interface was then implemented:
public string dropdown_value
{
get
{
return this._id.ToString();
}
}
public string dropdown_text
{
get
{
return String.Format("{0} ({1})", this._name, this._date.Year);
//Or simpler: return this._name;
}
}
}
The only thing left was to create a generic function that takes in a IDropdownable parameter and outputs the dropdownlist the way you like it (HTML string, SelectList, List<SelectListItem>, ... many options there).
public List<SelectListItem> GenerateDDL(
List<IDropdownable> items,
string selected_value)
{ ... }
If you want I can give you an approximation of the function.
Comment
We did this in MVC2 ASP.Net 4. To be honest, I'm not sure what type should be returned in classic ASP.NET, but I assume some type of List/Array will work.
I'm using Activator.CreateInstace() to create a generic instance. But when I use this to create a instance of an object:
public class SelectStageSaveData
{
public string GlobalPartnershipPoints { get; set; }
}
I get the message "Could not evaluate expression" when I'm debugging the code and trying to see GlobalPartnershipPoints. I've thought the value for this string were "empty" in this case, but I can't get any value. Does anyone know what is happening? Thanks in advance.
UPDATE:
Code where I create the instace:
if (!isolatedStorage.FileExists(file))
{
this.SaveData<T>((T)Activator.CreateInstance(typeof(T)), file);
}
or
if (!isolatedStorage.FileExists(file))
{
this.SaveData<T>(Activator.CreateInstance<T>(), file);
}
I get the same result with both.
I've thought the value for this string were "empty" in this case
Until you initialize the property, the value will be null by default. If you use a private field :
public class SelectStageSaveData
{
private string _GlobalPartnershipPoints = "";
public string GlobalPartnershipPoints
{
get { return _GlobalPartnershipPoints;}
set { _GlobalPartnershipPoints = value; }
}
}
Then you should get "" as default.
Hope it helps.