[c#] variables, ifs, simple math and drawing objects

Status
Not open for further replies.

jayfella

Active Member
Veteran
1,600
2009
565
680
Here is a little tutorial explains how to declare and use strings and integers, how to perform a basic integrity check and how to make use of these values by using an object. It also shows how to create these objects without using the Design view of Visual Studio.

The code has been commented to make it easier to read, and is fully functional. You can simply copy-paste its entirety into a new project.

PHP:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Here we are in the Form_Load function. Everything here is read when the form loads.
            // Right now nothing is being done, so lets assign something:

            // NOTE: we are using a boolean value (true or false) to decide whether to run these functions or not.

            // First declare the absolute size of our form, simply as a confirmation.
            this.Size = new Size(340, 110);

            simpleDeclarations(false); // Execute simpleDeclerations, our first example.

            drawButton(true); // Our second Example
        }

        private void simpleDeclarations(bool executeMe)
        {
            if (!executeMe) return; // if false, just quit right now, else continue.

            // Lets Assign some variables to play with
            string myString;
            int myInt;

            // Notice how we do not have to give either of these a "value" yet.
            // So lets assign them a value now.
            myString = "5";
            myInt = 3;

            // Ok - so lets visibly take a look at the values, just for fun :)
            MessageBox.Show("The Value of myString is: " + myString);
            MessageBox.Show("The Value of myInt is: " + myInt.ToString());

            // Notice that myInt needs to be converted to a string using ".ToString()" if we want to view it.
            // It would work if we didnt, but we are not leaving anything to chance.
            // MessageBoxes only allow string inputs. So thats what we are going to ensure it gets.

            // Ok - so lets play around a little. Lets do some math.
            int myTotal1 = (myInt + Int32.Parse(myString));
            int myTotal2 = (myInt * Int32.Parse(myString));

            // Notice how the string has to be converted to an integer. You can't add a string and an int together, of course.
            // So lets see the output to see if it worked:

            MessageBox.Show("MyTotal1 Value: " + myTotal1.ToString());
            MessageBox.Show("MyTotal1 Value: " + myTotal2.ToString());
            // Again, we are converting the integer to a string. Even if the .NET framework will "assume" this for you,
            // you should always ensure YOU know what your doing. Don't let the computer assume what it thinks you mean.
            // OK! so now we know how to do simple math using strings and integers, and how to convert strings to integers.

            // Converting integers to strings is easier:
            string tempString = myTotal1.ToString();

            // lets get a little more interesting....
            tempString = "hello world. The total cost is: " + myTotal1.ToString();

            // OK - so those are the basics. But we need to do some basic confirmations here. What if some of these variables are empty?
            // the integers and strings we created cannot be "null" - only zero-length for strings, and '0' for integers.

            if (myInt > 0)
                MessageBox.Show("MyInt has a value greater than zero.");
            else
                MessageBox.Show("myInt has a value of zero.");

            // Now, because this if/else statement is so small (a.k.a "one-liners") we dont need to use parenthesis. 
            // More of that later.
            // Lets check the value of our string to make sure its not empty and move on.

            if (tempString.Length == 0)
                MessageBox.Show("the string TemString has a length value of zero, so must be empty");
            else
                MessageBox.Show("the string TemString has a length greater than zero, so must contain data.");

            // Ok - so thats some basic checking.
            // Lets make this a little more interesting!
        }


        private void drawButton(bool executeMe)
        {
            if (!executeMe) return; // if false, just quit right now, else continue.
            
            Button myButton = new Button(); // Declare our new button and give it a unique id "myButton"
            myButton.Name = "button1"; // Give it a name
            myButton.Size = new Size(50, 23); // Set the size in pixels
            myButton.Location = new Point(10, 10); // Set its location
            myButton.Text = "Click Me"; // Set the visible text on the button
            myButton.Click += new EventHandler(letsPlay); // Declare what the button should do when clicked

            this.Controls.Add(myButton); // Finally, draw the button.
        }
        
        private void letsPlay(object sender, EventArgs e)
        {
            // We are going to make a little project here. We are going to draw a progressbar and make it move.#

            ProgressBar myProgressBar = new ProgressBar(); // Declare ur bar and give it a name "myProgressBar".
            myProgressBar.Size = new Size(300, 20); // Set the height/width of myProgressBar.
            myProgressBar.Location = new Point(10, 40); // Set the location of myProgressBar.

            this.Controls.Add(myProgressBar); // Add the control to the current forum (this).

            // OK - so here we have created a new instance of a progressBar, set its size and location and added it to the form.
            // So why do we have to tell the program to draw it, i hear you ask. Well we can configure as many controls as we
            // like - 10, 100, a thousand controls, and then draw them all at the same time - or we can draw them only when needed.
            // For example. Maybe i only want the progressBar to appear when i click a button? Who knows, but the point is
            // you have the CHOICE when to draw it. You will find this VERY useful once you start to rely less on the Designer.

            // So anyway, lets set some properties; the maximum and minimum value of the progressBar, and the current Value:

            myProgressBar.Maximum = 100; //  The maximum value myProgressBar can have.
            myProgressBar.Minimum = 0; // The minumum value myProgressBar can have.
            myProgressBar.Value = 0; // The current position of the progress bar;

            // Ok - so lets have a play with this bar.

            for (int i = 0; i <= 100; i++)
            {
                System.Threading.Thread.Sleep(20); // Pause for 20 hundredths of a second every second (simulate loading)
                myProgressBar.Value = i; // Set the value of the progressBar to the value of i
            }

            // We could also be a little more professional and show/hide visibility by using the property:
            // myProgressBar.Visible = bool;
            // For example, show the progressBar whilst myProgressBar.Value is greater than myProgressBar.Minimum and less than myProgressBar.Maximum
            // else, hide.

            // Notice how the GUI locks up? This is because we are using the parent thread to update the GUI, and since the loop
            // will not finish until the progressBar reaches 100%, the GUI gets locked until the loop finishes.
            // To get around this, we need to use THREADING and DELEGATES.
            // However, now is not the time. Have fun, enjoy!
        }
    }
}
 
23 comments
what ere the entities in the class declaration?

Code:
public partial class Form1 : Form
i know public,class, and what Form1 is but why is there a : Form and Partial keywords in the structure ?
 
Visual Studio uses partial classes to separate auto-generated code from user-generated code. Its as simple as that m8.

The :Form part just means use a regular form as described by the .net framework. You can use 3rd party tools like DevExpress or KryptonForms to use other types of form, and as such, the :Form will be replaced with :KryptonForm or w/e.
 
ok so the semi-colon is like implementing a 3rd parties class

So like in PHP Terms you would have a base class Called Form, and then MyClass that extends Form via :Form this brings the structure of :Form into the user class :)
 
Code:
public partial class myForm : Form
Means 2 things (that is, besides the obvious class declaration).

1) the class is partial. Meaning, the class is split across 2 source files.
2) ": Form" means myForm inherits the Form object. So the ":" here has the same meaning as PHP's "extends" keyword.
 
yea Hyperz, your answer to the : dilemma is what I interoperated jays answers as.

just one more thing.

You know when you have all your source files in your application such as

main.cs
object.someClass.cs

How are inclusions handled ? if i am right

use Litewarez.Security

does that load like

Litewarez/Security.cs or Litewarez.Security.cs

Im not sure how this works !

-- BTW i can ask questions all day long, you don't have to answer lool!
 
Well when you create your class, you can change it to:

namespace LiteWarez.Security

and then you call it by:

using LitwWarez.Security;

You dont have to do that.

You can instead do it like:

LiteWarez.Security.myStaticString(args);

which is better if you arent going to make use of the entire class.
 
so your saying that no matter what files you create there all included/loaded ready to be used!! even if there not being used by a particular process :/
 
yea i get it now, so that all cs files are mainly for the development of an application, once compiled it "combines" all files into a global assembly!
 
But you still have to declare it right? with "using" ?

Like in Hyperz thread:
Code:
using Hyperz.SharpLeech.Engine;

That way all the class, functions..etc he made are used/included, no?
 
yes el, it should take the same principles as all other languages.

If your creating a Form then you should do use System.Windows.Forms and then "extend" the class with :Form to use that base class.

Also: Hyperz or Jay.

if do the following:

using System.Windows

will that give me all children of Windows such as Forms or do i have to declare the exact name space ?

If you can use just use System.Windows then this would be bad right ? because your using unneeded shizzle!
 
In theory, even if that's possible you should only use exactly what you need, to have better speed, memory usage ..etc. I'm still new, very new with this, just using the same concept as scripting, not sure if that's right or even affects the outcome with C#.

Like including two files in PHP when you only need one, I guess.
 
i think im at the same level as yourself when it comes to C#, im just learning... i know it would be bad, im just learning if its possible. :)
 
Yeah. you can do that lite:

using System.Windows

will work fine, but you are basically loading all the child libraries from within it - which as el_j explained, its really not necessary.

Further to that, if you only want to make use of a single function, for example, "HttpWebRequest" - which is a child of System.Net - you can just do:

System.Net.HttpWebRequest webReq = new System.Net.HttpWebRequest;

rather than "using System.Net" and load the entire thing.

That way, you still get to use what you need, but don't load the entire library.
 
Status
Not open for further replies.
Back
Top