Variabel C # dan Tipe Data (Primitif)

Dalam tutorial ini, kita akan belajar tentang variabel, cara membuat variabel dalam C # dan tipe data berbeda yang didukung bahasa pemrograman C #.

Variabel adalah nama simbolis yang diberikan ke lokasi memori. Variabel digunakan untuk menyimpan data dalam program komputer.

Bagaimana cara mendeklarasikan variabel di C #?

Berikut adalah contoh untuk mendeklarasikan variabel di C #.

 int usia;

Dalam contoh ini, variabel jenis umur int(integer) dideklarasikan dan hanya dapat menyimpan nilai integer.

Kita dapat menetapkan nilai ke variabel nanti dalam program kita seperti:

 int usia;……… usia = 24;

Namun, variabel juga dapat diinisialisasi ke beberapa nilai selama deklarasi. Sebagai contoh,

 int usia = 24;

Di sini, usia variabel tipe intdideklarasikan dan diinisialisasi 24pada waktu yang sama.

Karena, ini adalah variabel, kita juga dapat mengubah nilai variabel. Sebagai contoh,

int usia = 24; usia = 35;

Di sini, nilai usia diubah menjadi 35 dari 24.

Variabel dalam C # harus dideklarasikan sebelum dapat digunakan. Artinya, nama dan jenis variabel harus diketahui sebelum dapat diberi nilai. Inilah mengapa C # disebut bahasa yang diketik secara statis.

Setelah dideklarasikan, tipe data variabel tidak dapat diubah dalam suatu lingkup. Cakupan dapat dianggap sebagai blok kode di mana variabel terlihat atau tersedia untuk digunakan. Jika Anda tidak memahami pernyataan sebelumnya, jangan khawatir kita akan belajar tentang cakupan di bab selanjutnya.

Untuk saat ini ingat, kita tidak dapat melakukan hal berikut di C #:

int usia; usia = 24;……… usia mengambang;

Variabel yang diketik secara implisit

Sebagai alternatif di C #, kita dapat mendeklarasikan variabel tanpa mengetahui tipenya menggunakan varkata kunci. Variabel semacam itu disebut variabel lokal yang diketik secara implisit .

Variabel yang dideklarasikan menggunakan varkata kunci harus diinisialisasi pada saat deklarasi.

 nilai var = 5;

Kompilator menentukan jenis variabel dari nilai yang diberikan ke variabel. Dalam contoh di atas, nilai adalah tipe int. Ini sama dengan:

nilai int; nilai = 5;

Anda dapat mempelajari lebih lanjut tentang variabel lokal yang diketik secara implisit.

Aturan Penamaan Variabel di C #

Ada aturan tertentu yang perlu kita ikuti saat menamai variabel. Aturan penamaan variabel di C # adalah:

  1. Nama variabel hanya boleh berisi huruf (huruf besar dan kecil), garis bawah (_), dan angka.
  2. Nama variabel harus dimulai dengan huruf, garis bawah, atau simbol @. Misalnya, Aturan penamaan variabel di C #
    Nama Variabel Catatan
    nama Sah
    subjek101 Sah
    _usia Valid (Praktik terbaik untuk menamai variabel anggota privat)
    @istirahat Valid (Digunakan jika nama adalah kata kunci yang dipesan)
    101subjek Tidak valid (Dimulai dengan digit)
    namamu Sah
    namamu Tidak valid (Berisi spasi)
  3. C # peka huruf besar / kecil. Artinya usia dan Usia mengacu pada 2 variabel berbeda.
  4. Nama variabel tidak boleh berupa kata kunci C #. Sebagai contoh, if, for, usingtidak bisa menjadi nama variabel. Kami akan membahas lebih lanjut tentang kata kunci C # di tutorial berikutnya.

Praktik Terbaik untuk Menamai Variabel

  1. Pilih nama variabel yang masuk akal. Misalnya, nama, usia, subjek lebih masuk akal daripada n, a dan s.
  2. Gunakan notasi camelCase (dimulai dengan huruf kecil) untuk penamaan variabel lokal. Misalnya, numberOfStudents, age, dll.
  3. Gunakan PascalCase atau CamelCase (dimulai dengan huruf besar) untuk menamai variabel anggota publik. Misalnya, FirstName, Price, dll.
  4. Gunakan garis bawah (_) diikuti dengan notasi camelCase untuk menamai variabel anggota pribadi. Misalnya, _bankBalance, _emailAddress, dll.

Anda dapat mempelajari lebih lanjut tentang konvensi penamaan di C # di sini.

Jangan khawatir tentang variabel anggota publik dan pribadi. Kita akan mempelajarinya di bab-bab selanjutnya.

C # Jenis Data Primitif

Variabel di C # secara luas diklasifikasikan menjadi dua jenis: Jenis nilai dan jenis Referensi . Dalam tutorial ini kita akan membahas tentang tipe data primitif (sederhana) yang merupakan subclass dari tipe Value.

Jenis referensi akan dibahas dalam tutorial selanjutnya. Namun, jika Anda ingin mengetahui lebih banyak tentang tipe variabel, kunjungi C # Jenis dan variabel (resmi C # dokumen).

Boolean (bool)

  • Tipe data Boolean memiliki dua kemungkinan nilai: trueataufalse
  • Nilai default :false
  • Variabel Boolean umumnya digunakan untuk memeriksa kondisi seperti di pernyataan if, loop, dll.

Sebagai contoh:

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

Saat kita menjalankan program, outputnya adalah:

 Benar

Integral yang ditandatangani

Tipe data ini memiliki nilai integer (baik positif maupun negatif). Dari total bit yang tersedia, satu bit digunakan untuk tanda.

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'; // karakter char ch2 = ' x0072'; // hexadecimal char ch3 = ' u0059'; // unicode char ch4 = (char) 107; // dicor dari integer
  • Literal string adalah kumpulan literal karakter.
  • Mereka diapit tanda kutip ganda. Misalnya, "Halo", "Pemrograman Mudah", dll.
    string firstName = "Richard"; string lastName = "Feynman";
  • C # juga mendukung karakter escape sequence seperti:
    Karakter Berarti
    \' Kutipan tunggal
    " Kutipan ganda
    \ Garis miring terbalik
    Garis baru
    Kereta kembali
    Tab Horizontal
    a Waspada
     Menghapus

Artikel yang menarik...