התחלת עבודה עם C#

על מנת לעבוד עם C# יש להתקין תחילה את Visual Studio. בהתקנה יש לבחור Net desktop Environment.

יצירת פרוייקט חדש

במסך הפתיחה נבחר Create New Project.

נבחר את C# בשפה, כ-pltform נבחר את Windows ואת Project type נבחר Console. סוג הפרוייקט יהיה Console App (.Net Framework).

ניתן שם לפרוייקט: MyFirstProject.

קובץ Program.cs

namespace MyFirstProject
{
    internal class Program
    {
        static void Main(string[] args) {
        }
    }
}

הפונקציה Main היא נקודת הכניסה לפרוייקט ה-console שלנו.

תוכנית Hello World

namespace MyFirstProject
{
    internal class Program
    {
        static void Main(string[] args) {
            Console.WriteLine("Hello World");
            Console.ReadLine();
        }
    }
}

פקודת WriteLine תכתוב מחרוזת לקונסול. פקודת ReadLine תתן השהייה כדי שיהיה אפשר לראות מה הודפס.

הרצה של הפרוייקט על ידי לחיצה על Start.

נראה את המחרוזת מודפסת בקונסול, לחיצה על מקש כלשהו תסגור את החלון.

Numeric data types

static void Main(string[] args) {
    int age = 23;
    long bigNumber = 9000000L;
    double negNum = -55.2;
    float percision = 5.0001F;
    decimal money = 40.99M;

    Console.WriteLine(int.MaxValue);
    Console.WriteLine(long.MaxValue);
    Console.WriteLine(double.MaxValue);
    Console.WriteLine(float.MaxValue);
    Console.WriteLine(decimal.MaxValue);

    Console.ReadLine();
}

Text based data types

static void Main(string[] args) {
    string name = "Aba";
    char letter = 'a';

    Console.Write("Your name is ");
    Console.Write(name);

    Console.ReadLine();
}

Converting string to numbers

static void Main(string[] args) {
    string textAge = "-23";
    int age = Convert.ToInt32(textAge);

    string textLong = "90000000";
    long BigNumber = Convert.ToInt64(textLong);

    string textNegative = "-55.3";
    double negative = Convert.ToDouble(textNegative);

    string textPercision = "5.000001";
    float percision = Convert.ToSingle(textPercision);

    string textMoney = "14.99";
    decimal money = Convert.ToDecimal(textMoney);
}

Boolean data type

static void Main(string[] args) {
    bool value = true;
}

Operators

static void Main(string[] args) {
    int age = 23;
    age++; // Add 1 to variable
    age--; // Minus 1 from variable
    age += 10; // age = age + 10
    age /= 10; // age = 2 the integer of 2.3

    double newAge = 23;
    newAge /= 10; // newAge = 2.3

    string name = "Jack";
    name += " is here"; // name = "Jack is here"

    // Reminder
    int firstNum = 10;
    int secondNum = 3;

    Console.WriteLine(firstNum / secondNum);  // = 3
    Console.WriteLine(firstNum % secondNum); // = 1
}

Var&Const keyword

שימוש ב-var יגרום לקומפיילר להתאים את סוג המשתנה לערך המוצב בו.

שימוש ב-const יגדיר משתנה קבוע שמקבל ערך בזמן ההגדרה שלו ולא ניתן לשנות את זה.

static void Main(string[] args) {
    var age = 12;
    const int vat = 17;
}

ניווט במאמר

מאמרים אחרונים

Weekly Tutorial