I'm learning C#, and I'm quite enjoying it. I have read through tutorials all over the net and cannot wrap my head around the concept behind classes, methods, objects, or namespaces. If anyone could run these through my head so an idiot could understand it would be appreciated. Or a link to a well written easy to understand tutorial would also be smiled upon. I know how to create them, I just don't know what they are used for or how they should be used.
1) Objects
Objects are basically bits of data stored in RAM. An int, string, FileStream, and Point are all examples of objects, once they are instantiated. (something becomes an object when you create an instance - eg: int x; Point p = new Point(5,10); etc.) That's when you can start using them - int x = 0; int y = 1; if (x != y) { Console.WriteLine("not equal"); }
2) Methods
A method is simply a function that you can call. There really isn't much to it...
There are different types of method returns though. You can create a method that returns a specific type like so (the function HAS to return an int):
[code]public int rollDice()
{
//Selected fairly from a random dice roll
return 4;
}[/code]
If you create classes or structs, you can also create a method that returns an instance of your class or struct (I'll talk about classes next).
3) Classes
Classes are the foundation of Object Oriented programming. If you want to disable a textbox, you call the "Enabled" property of the TextBox class (well, the specific instance you're using of the textbox class), and set it to False, and the class runs it's own code to gray out the textbox and not accept user input. A class should be thought of like a blueprint. You create everything you would need to make a house, but you don't actually create it yet. Now there are several blueprints needed to make a house, just like you need many labels, textboxes, and buttons to make a form. You have a Light class, a Sink class, a Room class, etc. So you create a bunch of Room classes, but they are all still empty. So now you create a bunch of instances of Lights, Sinks, etc. and set all their values just how you like. And all of a sudden, you have full control over every aspect of the room in a very easy-to-manage way.
Bathroom2.Large_Sink.Enabled = true; instead of Sink_25.Enabled = true;
It's much easier to read. Now this contains a lot of complicated concepts. Each item (eg Large_Sink) is instantiated and referenced in the Room class, similar to how a textbox is contained in a form class. It doesn't stop there, though. You can do even cooler things with classes, more specifically abstract classes.
So you create an abstract class Lamp, and fill it with all the variables and methods you need to get a basic lamp going, brightness, enabled, size, etc, but leave everything blank. You let someone else fill everything in (hence, abstract)
Then you create a class FloorLamp : Lamp (FloorLamp takes Lamp as a base), and fill in everything you need, from variables to the contents of all the methods. Anything referring to the Lamp class will also work with your FloorLamp class.
There's a lot you can do with Classes/OOP in general, I really suggest you buy a C# book which discusses it (pretty much all of them do)
3) namespaces
To my understanding, namespaces in C# are designed for one thing, organization. You can't have two methods or classes of the same name in one namespace, because calling that method name would cause the call to be ambiguous. If you move the second one over to another namespace, you can call MySecondNamespace.MyMethod(); and MyMethod();, and they would mean different things. You can also use it to organize your code (classes would work better in certain cases however, it's just something you need to get a feel for, most of my programs are contained under one namespace).
Also note that System, System.IO, etc. are all namespaces which you choose to make your code look a little cleaner. (you would call a System.IO.DirectoryInfo without "using System.IO;" at the top of the file)
These are just my ramblings, trying to explain everything the best that I can. You should really pick up a C# book and read through it if you want to fully understand everything. I'm also relatively new to OOP, so the more advanced class concepts are things I've yet to actually implement in a program of mine, and I'm just saying what I've read about it. I'm also not payed to write this, someone who writes a C# book is, however, paid to do so.
Note that all objects are classes. Even the built in types like int, string, long, even void. They are links to System.Int32, System.String, System.Int64, and System.Void respectively.
[QUOTE=slashsnemesis;24422992]I'm learning C#, and I'm quite enjoying it. I have read through tutorials all over the net and cannot wrap my head around the concept behind classes, methods, objects, or namespaces. If anyone could run these through my head so an idiot could understand it would be appreciated. Or a link to a well written easy to understand tutorial would also be smiled upon. I know how to create them, I just don't know what they are used for or how they should be used.[/QUOTE]
What's your past experience in programming?
Check out [url]http://en.wikipedia.org/wiki/Object-oriented_programming[/url] which should give you a nice summary to help further your understanding
[QUOTE=slashsnemesis;24422992]I'm learning C#, and I'm quite enjoying it. I have read through tutorials all over the net and cannot wrap my head around the concept behind classes, methods, objects, or namespaces. If anyone could run these through my head so an idiot could understand it would be appreciated. Or a link to a well written easy to understand tutorial would also be smiled upon. I know how to create them, I just don't know what they are used for or how they should be used.[/QUOTE]
A class is the blueprint for an object (instances of the class). When you define a class, you create a blueprint for instances of that class: you define what operations are valid on these instances, and what data they carry around. To define operations valid on your class' instances, you define [I]methods[/I], which I'll come back to. In C#, the term [I]object[/I] refers to instances of classes, but the term [I]instance[/I] is usually used when in the context of a particular class. It can also refer to the class called "Object", which is the root [I]base class[/I] for all other classes.
So what is a base class? Classes can extend the behaviour of other classes by [I]inheriting[/I] from them. If you don't explicitly inherit from another class, you will inherit directly from Object.
For example:
[cpp]
class A // A inherits Object
{
}
class B : A // B inherits A
{
}
[/cpp]
The point of all this is so instances of B can be treated as instances of A, and since instances of A can be treated as instances of Object, so can instances of B. So, for example, if you have an array of Object elements, the array can hold both A's and B's as well as instances of any other class.
To get an instantiated object from any of these classes, we use the [I]new[/I] operator:
[cpp]
A a = new A(); //variable 'a' of type A
B b = new B(); //variable 'b' of type B
a = b; // reassign 'a', still of type A, to the object in variable 'b', of type B.
[/cpp]
This is OK because B inherits A, so anything valid on an instance of A will be valid on an instance of B (but not the other way around), so objects that are actually of type B can be treated as A's. The typical (lame) example used to demonstrate this is the case of modeling animals: a [I]base class[/I] called Animal is inherited by classes Cat and Dog, so all Cat and Dog instances can be treated as Animals.
Finally, all objects can be given the Object type, because no matter what, their class inherits from Object somewhere down the line:
[cpp]
Object o = new B(); // OK
[/cpp]
So far classes A and B have been empty, which isn't very useful. They don't actually define any operations ([I]methods[/I]), so the only things you can do with them are things that are valid on Object's ([url=http://msdn.microsoft.com/en-us/library/e5kfa45b(v=VS.80).aspx]Object is not an empty class[/url]). There's a lot more to classes and objects, but if you understand the underlying concept, none of it should be difficult to pick up.
In some other languages, methods are often called [I]member functions[/I]. That's because they are functions, but functions which happen to operate on the instance of a class, or on the class itself (so-called [I]static methods[/I]). I'm not going to go into functions (also called [I]procedures[/I] or [I]subroutines[/I]), because while they're very basic, they're fundamental to programming and thus quite difficult to explain in short. For example, if you find a tutorial on functions (in any language you can read), most of it can be translated to C# methods (but I can't imagine there is any lack of C# specific tutorials).
Finally, the point of namespaces is to organize symbols. A symbol is any identifier; a class name, variable name, method name, etc. If it wasn't for namespaces, there could only ever be one class called Cat, Dog, Car, Manager, ManagerManager (you heard me), ManagerManagerManager (I bet you $10 someone did it), etc. in one application. This is a problem when you're using several libraries in one application and some of them decided to use similar names for their classes, which is more common than you might think.
(For example, the ever-so-popular Manager class! I will come around and punch you in the face if you ever use such a vague name for any of your classes :v:)
edit:
I'd love to answer any specific questions you might have about anything, though.
[QUOTE=Jawalt;24428326]What's your past experience in programming?[/QUOTE]
Well I've used Game Maker for a while, gave Python a try, was unable to make anything serious, gave VB 2008 a try, made some little things, some Lua, and I've tried C++ but I gave up on pointers v:v:v
[editline]05:32AM[/editline]
I really appreciate the time you both took to write those out, unless you just copied from a tutorial :v: I think I have a... decent understanding now. You lost me with this, though
[CODE]A a = new A();[/CODE]
What exactly is going on here?
It would also help if I could see a simple program that used classes and methods so I can see what they could be used for.
First a variable of type "A" called "a" is declared, usually meaning that the memory for that variable is now reserved. Then new A(); actually creates the instance of that class (A) and places a reference to that instance in "a".
Hope that makes sense.
[editline]05:24PM[/editline]
Also, someone correct me if this is wrong but:
If A is a struct, not a class. The actual value of that struct will be stored in "a", not a memory reference to it.
[QUOTE=slashsnemesis;24433201]Well I've used Game Maker for a while, gave Python a try, was unable to make anything serious, gave VB 2008 a try, made some little things, some Lua, and I've tried C++ but I gave up on pointers v:v:v
[editline]05:32AM[/editline]
I really appreciate the time you both took to write those out, unless you just copied from a tutorial :v: I think I have a... decent understanding now. You lost me with this, though
[CODE]A a = new A();[/CODE]
What exactly is going on here?
It would also help if I could see a simple program that used classes and methods so I can see what they could be used for.[/QUOTE]
Sorry, I wasn't sure how much you already knew. To build upon what was said above:
[cpp]
A a = new A(); //declares and initializes at the same time, preferred whenever possible
//To illustrate what that means, you can accomplish the same by doing:
A a; //declares variable 'a' of type 'A'.
Console.WriteLine(a); // error, 'a' is not initialized! Using uninitialized variables in C# is not allowed.
a = new A(); // assign 'a' to a freshly created instance of class A.
Console.WriteLine(a); // OK, 'a' has been given a meaningful value.
A b = a; // OK, 'b' refers to the same instance of A that we created earlier. (b is an alias for a)
[/cpp]
The reason 'b' in the above snippet is referring to the same instance as 'a' (as opposed to a copy) is because class instances in C# have [B]reference semantics[/B]. Any variable of type A is actually just a reference to an instance of A, and many references can point to the same instance. For example:
[cpp]
class A
{
public string Message = "Hello, world!";
}
static void ApplySuicidalTendencies(A victim)
{
victim.Message = "Good-bye, world!";
}
static void Main()
{
A a = new A();
Console.WriteLine(a.Message); //-> Hello, world!
ApplySuicidalTendencies(a); //pass 'a' to our depressed static method
Console.WriteLine(a.Message); //-> Good-bye, world!
}[/cpp]
As you can see, passing our 'a' variable to our unpleasant method doesn't pass a copy of the instance, but a [I]copy of the reference[/I]. The variable 'victim' inside our call refers to the same instance as our variable 'a' does.
Structs work differently. When you assign one struct variable to another, or pass a struct variable to a method, a copy is made, and changing things on one of the structs doesn't change things on the other. I don't think you should be thinking much about structs yet, but if you ever come across them, this is the biggest difference to keep in mind.
[QUOTE=slashsnemesis;24433201]Well I've used Game Maker for a while, gave Python a try, was unable to make anything serious, gave VB 2008 a try, made some little things, some Lua, and I've tried C++ but I gave up on pointers v:v:v
[editline]05:32AM[/editline]
I really appreciate the time you both took to write those out, unless you just copied from a tutorial :v: I think I have a... decent understanding now. You lost me with this, though
[CODE]A a = new A();[/CODE]What exactly is going on here?
It would also help if I could see a simple program that used classes and methods so I can see what they could be used for.[/QUOTE] You'd probably be better off learning something simple with very few things to learn. It'd be easier to grasp something simple, like a structured procedural language, you don't have to take my advice, I just personally found it easier to learn that way.
Lua is a good language to learn, at a basic level it's a procedural language with simple structuring, but the language exposes so much more, anonymous functions and tables can create class-like structures, and the metatable system is powerful and flexible.
That makes it more clear. I have a better understanding now. One more question, I do not quite understand when to use static or public or such or quite understand what they mean.
[QUOTE=slashsnemesis;24436904]That makes it more clear. I have a better understanding now. One more question, I do not quite understand when to use static or public or such or quite understand what they mean.[/QUOTE]
The [I]static[/I] keyword is not related to [I]public[/I]. What static means is that the data field (like Message up there) or method (like ApplySuicidalTendencies, which is indeed static!) belongs to the class itself instead of an instance of the class. That means that it can be called without having an instance of the class, and that the static method cannot access non-static data fields or methods (because they only exist on instances). For example, the Main method (program entry point) needs to be static, because it's not associated with any instance. ApplySuicidalTendencies (please don't make me spell that out any more) needs to be static too, because it's called from the static Main method.
Here's an example without such gratuitous use of static methods:
[cpp]
class UnstablePerson
{
//mood is private, which means only methods inside this class can use it.
private string mood = "Meh";
//Mood (capitalized) is a public property with a getter, but no setter.
//This means that the outside can read Mood, but they can't change it.
public string Mood
{
get{ return mood; }
}
//These two methods are public, which means anyone can use them.
public void MakeHappy()
{
mood = "Yay! :D";
}
public void MakeSad()
{
mood = "Nay :'(";
}
}
static void Main()
{
UnstablePerson person = new UnstablePerson();
Console.WriteLine(person.Mood); //-> Meh
person.MakeHappy();
Console.WriteLine(person.Mood); //-> Yay! :D
person.MakeSad();
Console.WriteLine(person.Mood); //-> Nay :'(
person.mood = "Calm"; //-> error! mood is private!
person.Mood = "Calm"; //-> error! Mood is read-only!
}
[/cpp]
This also introduces the notion of properties, and while I apologize for introducing something unrelated, I didn't want to use a dedicated getter method because that's pretty terrible practice in C#. What happens is, the getter (look for [B]get[/B] up there) is called every time Mood is read, as a sort of glorified getter method. Additionally, the setter would be called if you tried to change Mood, but since there is no setter, it's not allowed.
[QUOTE=jA_cOp;24437669]The [I]static[/I] keyword is not related to [I]public[/I]. What static means is that the data field (like Message up there) or method (like ApplySuicidalTendencies, which is indeed static!) belongs to the class itself instead of an instance of the class. That means that it can be called without having an instance of the class, and that the static method cannot access non-static data fields or methods (because they only exist on instances). For example, the Main method (program entry point) needs to be static, because it's not associated with any instance. ApplySuicidalTendencies (please don't make me spell that out any more) needs to be static too, because it's called from the static Main method.
Here's an example without such gratuitous use of static methods:
-snip-
This also introduces the notion of properties, and while I apologize for introducing something unrelated, I didn't want to use a dedicated getter method because that's pretty terrible practice in C#. What happens is, the getter (look for [B]get[/B] up there) is called every time Mood is read, as a sort of glorified getter method. Additionally, the setter would be called if you tried to change Mood, but since there is no setter, it's not allowed.[/QUOTE]
Ahh that makes much more sense now. Finally is there anything you think I should know before I continue learning? Any tips or such?
[QUOTE=slashsnemesis;24437924]Ahh that makes much more sense now. Finally is there anything you think I should know before I continue learning? Any tips or such?[/QUOTE]
Err... random tip: if you ever end up repeating yourself a lot in your code, make sure you're really taking the best approach (these kind of situations make for excellent questions on forums like these). Programmers are lazy, and modern programming involves trying to write things once and only once.
Also, keep asking good questions so I have something to write about :)
Just wondering but why did you use this?
[CODE]public string Mood
{
get{ return mood; }
} [/CODE]
Couldnt you of just done:
[CODE]public string Mood
{
return mood;
} [/CODE]
[QUOTE=Richy19;24438518]Just wondering but why did you use this?
[CODE]public string Mood
{
get{ return mood; }
} [/CODE]
Couldnt you of just done:
[CODE]public string Mood
{
return mood;
} [/CODE][/QUOTE]
Notice the lack of parentheses after 'Mood'. That's what makes it a property instead of a method, and properties must put code in get/set bodies.
edit:
MSDN has a good, short example on why properties are useful:
[url]http://msdn.microsoft.com/en-us/library/x9fsa0sw%28VS.80%29.aspx[/url]
[QUOTE=Richy19;24438518]Just wondering but why did you use this?
[CODE]public string Mood
{
get{ return mood; }
} [/CODE]
Couldnt you of just done:
[CODE]public string Mood
{
return mood;
} [/CODE][/QUOTE]
[URL="http://msdn.microsoft.com/en-us/library/aa287786(VS.71).aspx"]http://msdn.microsoft.com/en-us/library/aa287786(VS.71).aspx[/URL]
Sorry if I misunderstood.
Is that only in C# or is it in C++ as well?
I think I'm set for now, thanks for all the help :buddy:. If I encounter another difficulty in my programming adventures I will be sure to report back here for clarification.
Thank you to all that have contributed.
[QUOTE=Richy19;24438822]Is that only in C# or is it in C++ as well?[/QUOTE]
C++ uses getter and setter methods, not properties.
I don't know.
Btw, if there any reason why someone would do
public int Somethnig {
get {
return something;
}
set {
something=value;
}
}
?
Wouldn't it be easier to just set something as public?
I mean, I know what getters and setters are used for generally, but do they make sense in that example?
[code]
class Frog
{
int jump;
public:
int getJump() {return jump;}
void setJump(int newjump) {jump = newjump;}
};
[/code]
[editline]02:37PM[/editline]
[QUOTE=Darwin226;24438927]I don't know.
Btw, if there any reason why someone would do
public int Somethnig {
get {
return something;
}
set {
something=value;
}
}
?
Wouldn't it be easier to just set something as public?
I mean, I know what getters and setters are used for generally, but do they make sense in that example?[/QUOTE]
You broke my automerge, but generally it's good to have getters and setters on many occasions.
Think about an Angle3 class, what if I want to clamp the value between 0-360? If I did that in every piece of code I set the value of an angle, that's error prone, but instead I use a getter and setter.
[QUOTE=Darwin226;24438927]I don't know.
Btw, if there any reason why someone would do
-snip-
?
Wouldn't it be easier to just set something as public?
I mean, I know what getters and setters are used for generally, but do they make sense in that example?[/QUOTE]
Indeed there is no difference, the point is that they can be used interchangeably, so the implementation can freely switch between public fields and properties.
[QUOTE=Richy19;24438822]Is that only in C# or is it in C++ as well?[/QUOTE]
C++ doesn't have properties, hence public fields in classes is often considered bad practice, you're advised to use getters and setters from the start, so that if you need to add more elaborate getting/setting later, client code remains unchanged. Notice how you don't see any public fields in the C++ standard library. Same theory goes for Java.
Well, as I said. I know what they are used for but in the example I gave there is no difference. Just more stuff to write.
Also, I don't think you should clamp angles. 365 != 360, it's 5.
[QUOTE=Darwin226;24439052]Well, as I said. I know what they are used for but in the example I gave there is no difference. Just more stuff to write.[/QUOTE]
Real examples won't do that, it's just to illustrate. You might still see it in real code, but that's only because people recognize that they'll probably need elaborate setters or getters later.
[QUOTE=Darwin226;24439052]Well, as I said. I know what they are used for but in the example I gave there is no difference. Just more stuff to write.
Also, I don't think you should clamp angles. 365 != 360, it's 5.[/QUOTE] Well I didn't mean clamp, I guess 'wrap' would be a better word.
[QUOTE=Darwin226;24438927]I don't know.
Btw, if there any reason why someone would do
public int Somethnig {
get {
return something;
}
set {
something=value;
}
}
?
Wouldn't it be easier to just set something as public?
I mean, I know what getters and setters are used for generally, but do they make sense in that example?[/QUOTE]
As of .NET 3.0, you can shorten that to:
[cpp]public int Somethnig { get; set; }[/cpp]
-snip-
[QUOTE=Skuch;24441982]Speaking of getting into the syntax and Object Orientated Programming, you should try out coding PHP. Nothing serious, but it's a good start to learn both syntax and functionality. Even though it is two totally different things, it could be a good place to start.[/QUOTE]
He wants to learn C#. PHP is entirely unrelated. There's no reason to take a detour into a different language unless the language he's trying to learn is unstable, has very little documentation etc. which C# is most certainly not.
Sorry, you need to Log In to post a reply to this thread.