C # -Variablen und (primitive) Datentypen

In diesem Tutorial erfahren Sie mehr über Variablen, das Erstellen von Variablen in C # und verschiedene Datentypen, die von der Programmiersprache C # unterstützt werden.

Eine Variable ist ein symbolischer Name, der einem Speicherort zugewiesen wird. Variablen werden verwendet, um Daten in einem Computerprogramm zu speichern.

Wie deklariere ich Variablen in C #?

Hier ist ein Beispiel zum Deklarieren einer Variablen in C #.

 int Alter;

In diesem Beispiel wird ein variables Alter vom Typ int(Ganzzahl) deklariert, in dem nur Ganzzahlwerte gespeichert werden können.

Wir können der Variablen später in unserem Programm einen Wert zuweisen, wie folgt:

 int Alter; …… Alter = 24;

Die Variable kann jedoch auch während der Deklaration auf einen bestimmten Wert initialisiert werden. Beispielsweise,

 int age = 24;

Hier wird gleichzeitig ein variables Typalter intdeklariert und initialisiert 24.

Da es sich um eine Variable handelt, können wir auch den Wert von Variablen ändern. Beispielsweise,

int age = 24; Alter = 35;

Hier wird der Wert des Alters von 24 auf 35 geändert.

Variablen in C # müssen deklariert werden, bevor sie verwendet werden können. Dies bedeutet, dass Name und Typ der Variablen bekannt sein müssen, bevor ihnen ein Wert zugewiesen werden kann. Aus diesem Grund wird C # als statisch typisierte Sprache bezeichnet.

Einmal deklariert, kann der Datentyp einer Variablen nicht innerhalb eines Bereichs geändert werden. Ein Bereich kann als Codeblock betrachtet werden, in dem die Variable sichtbar oder zur Verwendung verfügbar ist. Wenn Sie die vorherige Aussage nicht verstehen, machen Sie sich keine Sorgen, wir werden in den späteren Kapiteln mehr über Bereiche erfahren.

Denken Sie vorerst daran, dass wir in C # Folgendes nicht tun können:

int Alter; Alter = 24; …… Float-Alter;

Implizit typisierte Variablen

Alternativ können wir in C # eine Variable deklarieren, ohne ihren Typ mithilfe des varSchlüsselworts zu kennen. Solche Variablen werden implizit typisierte lokale Variablen genannt .

Mit dem varSchlüsselwort deklarierte Variablen müssen zum Zeitpunkt der Deklaration initialisiert werden.

 var value = 5;

Der Compiler bestimmt den Variablentyp aus dem Wert, der der Variablen zugewiesen ist. Im obigen Beispiel ist der Wert vom Typ int. Dies entspricht:

int value; Wert = 5;

Sie können mehr über implizit typisierte lokale Variablen erfahren.

Regeln zum Benennen von Variablen in C #

Es gibt bestimmte Regeln, die wir beim Benennen einer Variablen befolgen müssen. Die Regeln für die Benennung einer Variablen in C # lauten:

  1. Der Variablenname kann nur Buchstaben (Groß- und Kleinbuchstaben), Unterstriche (_) und Ziffern enthalten.
  2. Der Variablenname muss entweder mit einem Buchstaben, einem Unterstrich oder einem @ -Symbol beginnen. Beispiel: Regeln zum Benennen von Variablen in C #
    Variablennamen Bemerkungen
    Name Gültig
    subject101 Gültig
    _Alter Gültig (Best Practice zum Benennen privater Mitgliedsvariablen)
    @brechen Gültig (Wird verwendet, wenn name ein reserviertes Schlüsselwort ist)
    101subject Ungültig (Beginnt mit Ziffer)
    Ihren Namen Gültig
    Ihren Namen Ungültig (enthält Leerzeichen)
  3. C # unterscheidet zwischen Groß- und Kleinschreibung. Es bedeutet, dass Alter und Alter sich auf 2 verschiedene Variablen beziehen.
  4. Ein Variablenname darf kein C # -Schlüsselwort sein. Zum Beispiel if, for, usingkann nicht ein Variablenname. Wir werden im nächsten Tutorial mehr über C # -Schlüsselwörter diskutieren.

Best Practices für die Benennung einer Variablen

  1. Wählen Sie einen sinnvollen Variablennamen. Zum Beispiel sind Name, Alter, Thema sinnvoller als n, a und s.
  2. Verwenden Sie die camelCase- Notation (beginnt mit Kleinbuchstaben), um lokale Variablen zu benennen. Zum Beispiel Anzahl der Studenten, Alter usw.
  3. Verwenden Sie PascalCase oder CamelCase (beginnt mit Großbuchstaben), um öffentliche Mitgliedsvariablen zu benennen. Zum Beispiel Vorname, Preis usw.
  4. Verwenden Sie einen führenden Unterstrich (_) gefolgt von der camelCase- Notation, um private Mitgliedsvariablen zu benennen. Zum Beispiel _bankBalance, _emailAddress usw.

Weitere Informationen zu Namenskonventionen in C # finden Sie hier.

Machen Sie sich keine Sorgen über öffentliche und private Mitgliedsvariablen. Wir werden in späteren Kapiteln mehr darüber erfahren.

C # Primitive Datentypen

Variablen in C # werden grob in zwei Typen eingeteilt: Werttypen und Referenztypen . In diesem Tutorial werden wir uns mit primitiven (einfachen) Datentypen befassen, die eine Unterklasse von Werttypen sind.

Referenztypen werden in späteren Tutorials behandelt. Wenn Sie jedoch mehr über Variablentypen erfahren möchten, besuchen Sie C # -Typen und -Variablen (offizielle C # -Dokumente).

Boolean (Bool)

  • Der boolesche Datentyp hat zwei mögliche Werte: trueoderfalse
  • Standardwert :false
  • Boolesche Variablen werden im Allgemeinen verwendet, um Bedingungen wie if-Anweisungen, Schleifen usw. zu überprüfen.

Beispielsweise:

 using System; namespace DataType ( class BooleanExample ( public static void Main(string() args) ( bool isValid = true; Console.WriteLine(isValid); ) ) )

Wenn wir das Programm ausführen, lautet die Ausgabe:

 Wahr

Signiertes Integral

Diese Datentypen enthalten ganzzahlige Werte (sowohl positive als auch negative). Von den insgesamt verfügbaren Bits wird ein Bit für das Vorzeichen verwendet.

1. sbyte

  • Size: 8 bits
  • Range: -128 to 127.
  • Default value: 0

For example:

 using System; namespace DataType ( class SByteExample ( public static void Main(string() args) ( sbyte level = 23; Console.WriteLine(level); ) ) )

When we run the program, the output will be:

 23

Try assigning values out of range i.e. less than -128 or greater than 127 and see what happens.

2. short

  • Size: 16 bits
  • Range: -32,768 to 32,767
  • Default value: 0

For example:

 using System; namespace DataType ( class ShortExample ( public static void Main(string() args) ( short value = -1109; Console.WriteLine(value); ) ) )

When we run the program, the output will be:

 -1109

3. int

  • Size: 32 bits
  • Range: -231 to 231-1
  • Default value: 0

For example:

 using System; namespace DataType ( class IntExample ( public static void Main(string() args) ( int score = 51092; Console.WriteLine(score); ) ) )

When we run the program, the output will be:

 51092

4. long

  • Size: 64 bits
  • Range: -263 to 263-1
  • Default value: 0L (L at the end represent the value is of long type)

For example:

 using System; namespace DataType ( class LongExample ( public static void Main(string() args) ( long range = -7091821871L; Console.WriteLine(range); ) ) )

When we run the program, the output will be:

 -7091821871

Unsigned Integral

These data types only hold values equal to or greater than 0. We generally use these data types to store values when we are sure, we won't have negative values.

1. byte

  • Size: 8 bits
  • Range: 0 to 255.
  • Default value: 0

For example:

 using System; namespace DataType ( class ByteExample ( public static void Main(string() args) ( byte age = 62; Console.WriteLine(level); ) ) )

When we run the program, the output will be:

 62

2. ushort

  • Size: 16 bits
  • Range: 0 to 65,535
  • Default value: 0

For example:

 using System; namespace DataType ( class UShortExample ( public static void Main(string() args) ( ushort value = 42019; Console.WriteLine(value); ) ) )

When we run the program, the output will be:

 42019

3. uint

  • Size: 32 bits
  • Range: 0 to 232-1
  • Default value: 0

For example:

 using System; namespace DataType ( class UIntExample ( public static void Main(string() args) ( uint totalScore = 1151092; Console.WriteLine(totalScore); ) ) )

When we run the program, the output will be:

 1151092

4. ulong

  • Size: 64 bits
  • Range: 0 to 264-1
  • Default value: 0

For example:

 using System; namespace DataType ( class ULongExample ( public static void Main(string() args) ( ulong range = 17091821871L; Console.WriteLine(range); ) ) )

When we run the program, the output will be:

 17091821871

Floating Point

These data types hold floating point values i.e. numbers containing decimal values. For example, 12.36, -92.17, etc.

1. float

  • Single-precision floating point type
  • Size: 32 bits
  • Range: 1.5 × 10−45 to 3.4 × 1038
  • Default value: 0.0F (F at the end represent the value is of float type)

For example:

 using System; namespace DataType ( class FloatExample ( public static void Main(string() args) ( float number = 43.27F; Console.WriteLine(number); ) ) )

When we run the program, the output will be:

 43.27

2. double

  • Double-precision floating point type. What is the difference between single and double precision floating point?
  • Size: 64 bits
  • Range: 5.0 × 10−324 to 1.7 × 10308
  • Default value: 0.0D (D at the end represent the value is of double type)

For example:

 using System; namespace DataType ( class DoubleExample ( public static void Main(string() args) ( double value = -11092.53D; Console.WriteLine(value); ) ) )

When we run the program, the output will be:

 -11092.53

Character (char)

  • It represents a 16 bit unicode character.
  • Size: 16 bits
  • Default value: ''
  • Range: U+0000 ('u0000') to U+FFFF ('uffff')

For example:

 using System; namespace DataType ( class CharExample ( public static void Main(string() args) ( char ch1 ='u0042'; char ch2 = 'x'; Console.WriteLine(ch1); Console.WriteLine(ch2); ) ) ) 

When we run the program, the output will be:

 B x

The unicode value of 'B' is 'u0042', hence printing ch1 will print 'B'.

Decimal

  • Decimal type has more precision and a smaller range as compared to floating point types (double and float). So it is appropriate for monetary calculations.
  • Size: 128 bits
  • Default value: 0.0M (M at the end represent the value is of decimal type)
  • Range: (-7.9 x 1028 to 7.9 x 1028) / (100 to 28)

For example:

 using System; namespace DataType ( class DecimalExample ( public static void Main(string() args) ( decimal bankBalance = 53005.25M; Console.WriteLine(bankBalance); ) ) ) 

When we run the program, the output will be:

 53005.25

The suffix M or m must be added at the end otherwise the value will be treated as a double and an error will be generated.

C# Literals

Let's look at the following statement:

 int number = 41;

Here,

  • int is a data type
  • number is a variable and
  • 41 is a literal

Literals are fixed values that appear in the program. They do not require any computation. For example, 5, false, 'w' are literals that appear in a program directly without any computation.

Boolean Literals

  • true and false are the available boolean literals.
  • They are used to initialize boolean variables.

For example:

 bool isValid = true; bool isPresent = false;

Integer Literals

  • Integer literals are used to initialize variables of integer data types i.e. sbyte, short, int, long, byte, ushort, uint and ulong.
  • If an integer literal ends with L or l, it is of type long. For best practice use L (not l).
     long value1 = 4200910L; long value2 = -10928190L;
  • If an integer literal starts with a 0x, it represents hexadecimal value. Number with no prefixes are treated as decimal value. Octal and binary representation are not allowed in C#.
     int decimalValue = 25; int hexValue = 0x11c;// decimal value 284

Floating Point Literals

  • Floating point literals are used to initialize variables of float and double data types.
  • If a floating point literal ends with a suffix f or F, it is of type float. Similarly, if it ends with d or D, it is of type double. If neither of the suffix is present, it is of type double by default.
  • These literals contains e or E when expressed in scientific notation.
     double number = 24.67;// double by default float value = -12.29F; double scientificNotation = 6.21e2;// equivalent to 6.21 x 102 i.e. 621

Character and String Literals

  • Character literals are used to initialize variables of char data types.
  • Character literals are enclosed in single quotes. For example, 'x', 'p', etc.
  • They can be represented as character, hexadecimal escape sequence, unicode representation or integral values casted to char.
     char ch1 = 'R'; // Zeichen char ch2 = ' x0072'; // hexadezimales Zeichen ch3 = ' u0059'; // Unicode char ch4 = (char) 107; // aus Ganzzahl umgewandelt
  • String-Literale sind die Sammlung von Zeichenliteralen.
  • Sie sind in doppelte Anführungszeichen eingeschlossen. Zum Beispiel "Hallo", "Einfache Programmierung" usw.
    Zeichenfolge Vorname = "Richard"; Zeichenfolge lastName = "Feynman";
  • C # unterstützt auch Escape-Sequenzzeichen wie:
    Charakter Bedeutung
    \' Einfaches Zitat
    " Doppeltes Zitat
    \ Backslash
    Neue Zeile
    Wagenrücklauf
    Horizontale Registerkarte
    a Aufmerksam
     Rücktaste

Interessante Beiträge...