C# classes init function - c#

I am learning c#, having used python before, and i have started to use classes in my work.
Python has the __init__() function to initialise a class, for example:
class name():
__init__(self):
# this code will run when the class is first made
Is there a similar function for c# classes?
currently, I am creating a normal function inside the class and having to call it straight after it is made.

You have to use one or more constructor for that:
see this link on learn.microsoft.com.
For example:
public class Person
{
private string last;
private string first;
// This constructor is called a default constructor.
// If you put nothing in it, it will just instanciate an object
// and set the default value for each field: for a reference type,
// it will be null for instance. String is a reference type,
// so both last and first will be null.
public Person()
{}
// This constructor will instanciate an object an set the last and first with string you provide.
public Person(string lastName, string firstName)
{
last = lastName;
first = firstName;
}
}
class Program
{
static void Main(string[] args)
{
// last and first will be null for myPerson1.
Person myPerson1 = new Person();
// last = Doe and first = John for myPerson2.
Person myPerson2 = new Person("Doe", "John");
}
}

Your talking about constructor in c#
class MyClass{
public MyClass{ //this is the constructor equals to pythons init
}
}
These concepts are available in almost all languages with different format

You should start building a constructor like this:
public class Car
{
public string plateNumber {get; set;}
public Car(string platenumber)
{
this.plateNumber = platenumber;
}
}
And then initialize an instance of it in another form or class like so:
Car myCar = new Car("123abc");

Related

Possible way of initializing constructor/object

I'm beginner when it comes to OOP. Yesterday I was trying to read some mvvm/wpf examples and of course I get into trouble... I have some problem with understand some of code below:
{
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Addres { get; set; }
}
This is just normal Person class, nothing really unusal here. The problem is that I can't understand below code:
private void SayHi_Click(object sender, RoutedEventArgs e)
{
Person person = new Person
{
FirstName=FirstName.Text,
LastName=LastName.Text,
Addres=Address.Text
};
The part that I do not understand is:
Person person = new Person
{
FirstName=FirstName.Text,
LastName=LastName.Text,
Addres=Address.Text
};
I'm not sure what this is exactly. I thought that every new object should be initialized like this one: Class class = new Class();. Why there is no () after "new Person"? Instead of () we have {}. I know that we can use default, parameterized, static and private construcotrs. Could someone explain this to me? Similar situation in below tutorial from CodeProject:
http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial
We have a Song Class
public class Song
{
#region Members
string _artistName;
string _songTitle;
#endregion
#region Properties
/// The artist name.
public string ArtistName
{
get { return _artistName; }
set { _artistName = value; }
}
/// The song title.
public string SongTitle
{
get { return _songTitle; }
set { _songTitle = value; }
}
#endregion
}
And we have of course View Model for this class:
public class SongViewModel
{
Song _song;
public Song Song
{
get
{
return _song;
}
set
{
_song = value;
}
}
public string ArtistName
{
get { return Song.ArtistName; }
set { Song.ArtistName = value; }
}
}
And again, this part of code is something that I can't understand:
public class SongViewModel
{
Song _song;
public Song Song
What this "Song _song;" is? This is object of Song Class? And this Property "Song Song" is also wierd... Probably I have a lack of knowledge
I had to leave a new answer here, because I have seen 2 people get it wrong. The initializer syntax:
Person person = new Person
{
FirstName = FirstName.Text,
LastName = LastName.Text,
Address = Address.Text
};
Is not exactly equivalent to creating a new variable "person" and then assigning the properties. Rather, it is equivalent to creating a temp variable, assigning the properties, and then assigning the result to "person":
Person person;
var temp = new Person();
temp.FirstName = FirstName.Text;
temp.LastName = LastName.Text;
temp.Address = Address.Text;
person = temp;
The distinction can actually be quite important, especially working in a view model. You should be able to see this, if you imagine that you are assigning to a property whose setter raises the "PropertyChanged" event, which in turn has one or more view elements listening to it. Using the temp variable results in a big performance gain, because every event listener gets fired only once, rather than twice (once when the Person property is set, and then again when each of its properties are initialized).
The provided code is using an Object Initializer (MSDN)
From that page:
Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements. The object initializer syntax enables you to specify arguments for a constructor or omit the arguments (and parentheses syntax).
Basically, it means you don't need the (), and can specify public field/property values in the {}.
Also; find a different site to learn MVVM. Directly creating Model/ViewModel objects from the UI is a big no-no.
This:
Person person = new Person
{
FirstName=FirstName.Text,
LastName=LastName.Text,
Addres=Address.Text
};
And:
Person person = new Person();
person.FirstName=FirstName.Text;
person.LastName=LastName.Text;
person.Addres=Address.Text;
Are equivalent. The first is syntactic sugar.

C# How to create special instances of a class?

For some classes, ideally, I'd like to create special named instances, similar to "null." As far as I know, that's not possible, so instead, I create static instances of the class, with a static constructor, similar to this:
public class Person
{
public static Person Waldo; // a special well-known instance of Person
public string name;
static Person() // static constructor
{
Waldo = new Person("Waldo");
}
public Person(string name)
{
this.name = name;
}
}
As you can see, Person.Waldo is a special instance of the Person class, which I created because in my program, there are a lot of other classes that might want to refer to this special well-known instance.
The downside of implementing this way is that I don't know any way to make all the properties of Person.Waldo immutable, while all the properties of a "normal" Person instance should be mutable. Whenever I accidentally have a Person object referring to Waldo, and I carelessly don't check to see if it's referring to Waldo, then I accidentally clobber Waldo's properties.
Is there a better way, or even some additional alternative ways, to define special well-known instances of a class?
The only solution I know right now, is to implement the get & set accessors, and check "if ( this == Waldo) throw new ..." on each and every set. While this works, I assume C# can do a better job than me of implementing it. If only I can find some C# way to make all the properties of Waldo readonly (except during static constructor.)
Make a private class inside the Person that inherits the Person, ImmutablePerson : Person.
Make all the property setters locked up: override them with NotImplementedException for instance.
Your static Person initialization becomes this:
public static readonly Person Waldo = new ImmutablePerson("Waldo");
And static constructor may be removed, too.
Maybe you could have the following hierarchy:
class Person
{
protected string _name;
public virtual string Name{
get{
return _name;
}
}
}
class EditablePerson:Person
{
public new string Name{
get{
return _name;
}
set{
_name=value;
}
}
public Person AsPerson()
{
//either return this (and simply constrain by interface)
//or create an immutable copy
}
}
In my opinion the best is to return always a new instance on Waldo. This way the original Waldo will never be changed. But this will prevent you from using reference equality for comparison, therefore you will have to override Equals and GetHashCode.
Thanks to all your suggestions - Here is the solution. I needed to make string virtual, override the accessors in a public derivative class, and use a bool flag to permit modification.
It's important to note, that "name" is a reference type, and although I've prevented changing what "name" refers to, if it were something other than a string, such as a class that contains a self-modification method, it could still be possible to modify the contents of the object, despite having prevented modification to the object reference.
class Program
{
static void Main(string[] args)
{
Person myPerson = new Person("Wenda");
System.Console.WriteLine("myPerson is " + myPerson.name); // Prints "myPerson is Wenda"
if (myPerson == Person.Waldo)
System.Console.WriteLine("Found Waldo (first attempt)"); // doesn't happen
else
System.Console.WriteLine("Still trying to find Waldo..."); // Prints "Still trying to find Waldo..."
myPerson.name = "Bozo";
System.Console.WriteLine("myPerson is now " + myPerson.name); // Prints "myPerson is now Bozo"
myPerson = Person.Waldo;
if (myPerson == Person.Waldo)
System.Console.WriteLine("Found Waldo (second attempt)"); // Prints "Found Waldo (second attempt)"
System.Console.WriteLine("myPerson is " + myPerson.name); // Prints "myPerson is Waldo"
System.Console.WriteLine("Now changing to The Joker..."); // Prints "Now changing to The Joker"
try
{
myPerson.name = "The Joker"; // throws ImmutablePersonModificationAttemptException
}
catch (ImmutablePersonModificationAttemptException)
{
System.Console.WriteLine("Failed to change"); // Prints "Failed to change"
}
System.Console.WriteLine("myPerson is now " + myPerson.name); // Prints "myPerson is now Waldo"
Thread.Sleep(int.MaxValue); // keep the console alive long enough for me to see the result.
}
}
public class Person
{
public static readonly ImmutablePerson Waldo = new ImmutablePerson("Waldo");
public virtual string name { get; set; }
public Person() // empty base constructor required by ImmutablePerson(string) constructor
{ }
public Person(string name)
{
this.name = name;
}
}
public class ImmutablePersonModificationAttemptException : Exception
{ }
public class ImmutablePerson : Person
{
private bool allowMutation;
protected string _name;
public override string name
{
get
{
return _name;
}
set
{
if (allowMutation)
_name = value;
else
throw new ImmutablePersonModificationAttemptException();
}
}
public ImmutablePerson(string name)
: base()
{
allowMutation = true;
this.name = name;
allowMutation = false;
}
}

Writing method without declaring type of that

in some documentation i saw some methods that were written without declaring type of that(e.g void,string,int,etc...). like this:
public ActorRecord()
{
ActorMovies = new List<MovieActorRecord>();
}
or
private readonly ITaxonomyService _taxonomyService;
private readonly IContentManager _contentManager;
public MovieFeatureEventHandler(ITaxonomyService taxonomyService, IContentManager contentManager)
{
_taxonomyService = taxonomyService;
_contentManager = contentManager;
}
what does these methods do.
what is diffrence between | public ActorRecord() and public void/string ActorRecord() | ?
You could have noticed that those methods also have the exact same name as the class (or struct) that they are in.
They are called constructors.
Q: what is diffrence between public ActorRecord() and public void ActorRecord() ?
A: Inside a class ActorRecord {}, the first is a constructor and the second is a syntax error.
The methods in questions are called constructors. When you create a new instance of an object the code inside the constructor method is called to 'set up' the object in question.
For example
Public Class Thing
{
private int _amount;
public Thing()
{
_amount = 5;
}
}
If I call this code:
var thing = new Thing();
Then a will get a new Thing with an _amount variable of '5'
If you add the void than it will become a normal method and be called like other methods:
thing.Thing()

Why are my values not being kept between instances of a type?

I have the class:
public class pro {
private string url = string.Empty;
public string GetURL() { return url; }
public void SetURL(string value) { url = value; }
}
In this line I'm getting value:
string url = li1.Value;
pro itm = new pro(); // I have create Proprtie so I'm calling that
itm.SetURL(url); // here I'm setting value
Then later:
pro itm = new pro(); //properties object I have created
string url = itm.GetURL(); // I'm not getting value which I have set in first
class.
I have create Proprties also; what am I doing wrong?
May be I understood your problem :
The thing is that in second you create a new instance of pro class. If you want to acess the string value set in first class, you should use that first pro object.
If it's not your problem, please clarify.
Every class instance (i.e. every new pro()) has different instance values; it is perfectly expected that if you have 2 different instances, then they will not share a URL, for example. If you want to share this, you should make the same pro instance available to both places, by passing the pro around.
Incidentally, GetURL() / SetURL() is not idiomatic C# - it would be more common to have a property, i.e.
public string Url {get;set;}
which you would then access as:
YourType item = new YourType();
item.Url = "http://foo.com/bar/";
// ...
string url = item.Url;
From the comments, it sounds like you are talking about static data; I should emphasise that using static for this is not usually a good idea, and can lead to lots of problems with testing, multi-tenancy, threading, etc; but: the following works without any instances:
public class Properties {
public static string Url {get;set;}
}
...
Properties.Url = "http://foo.com/bar/";
...
string url = Properties.Url;
note: no instances at all.
However, it is almost always preferable to simply keep an instance available, and use instance properties against that common instance.
If you need to have some class like application properties you can use static class.
public static class pro
{
public static string Url {get; set;}
}
and use it like pro.Url = "aa";

The this reference? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When do you use the “this” keyword?
Can anyone explain me the "this" reference? when we use this ? with a simple example.
When you use this inside a class, you're refering to the current instance: to the instance of that class.
public class Person {
private string firstName;
private string lastName;
public Person(string firstName, string lastName) {
//How could you set the first name passed in the constructor to the local variable if both have the same?
this.firstName = firstName;
this.lastName = lastName;
}
//...
}
In the above example, this.firstName is refering to the field firstName of the current instance of the class Person, and firstName (the right part of the assignment) refers to the variable defined in the scope of the constructor.
So when you do:
Person me = new Person("Oscar", "Mederos")
this refers to the instance Person instance me.
Edit:
As this refers to the class instance, cannot be used inside static classes.
this is used (too) to define indexers in your classes, like in arrays: a[0], a["John"],...
this is a scope identifier. It is used within an object's instance methods to identify behaviors and states that belong to an instance of the class.
Nowadays-fashionable Fluent APIs use this extensively. Basically it's used to get hold of a reference to the current instance.
here's a simple example
public class AnObject
{
public Guid Id { get; private set;}
public DateTime Created {get; private set; }
public AnObject()
{
Created = DateTime.Now;
Id = Guid.NewGuid();
}
public void PrintToConsole()
{
Console.WriteLine("I am an object with id {0} and I was created at {1}", this.Id, this.Created); //note that the the 'this' keyword is redundant
}
}
public Main(string[] args)
{
var obj = new AnObject();
obj.PrintToConsole();
}

Categories

Resources