Kiểu dữ liệu trong C#

Kiểu dữ liệu trong C#

Phân loại kiểu dữ liệu

Các biến trong C# được phân loại thành 3 kiểu sau:

  • Kiểu giá trị (Value type)
  • Kiểu tham chiếu (Reference type)
  • Kiểu con trỏ (Pointer type)

Bộ nhớ Stack và Heap

Trong C# có hai loại bộ nhớ là Stack và Heap. Cả hai đều là những vùng nhớ được lưu trữ trên RAM.

Stack là vùng nhớ hoạt động theo mô hình LIFO (vào sau, ra trước) dùng để lưu trữ các biến tạm thời được tạo ra bởi các phương thức. Khi một biến được khai báo, nó được tự động đẩy vào stack (push).

Nếu phương thức kết thúc, tất cả các biến mà phương thức đó đã đẩy vào stack đều bị giải phóng (pop) và mất đi. Khi một biến bị đẩy khỏi stack, vùng nhớ nó đã chiếm có thể được sử dụng lại cho các biến khác.

Stack được CPU quản lý và tối ưu hóa cho nhiệm vụ lưu trữ biến cục bộ. Người lập trình không cần phải can thiệp vào vùng nhớ này. Tốc độ đọc ghi dữ liệu với stack rất cao, tuy nhiên kích thước của stack lại bị giới hạn.

Heap là một vùng nhớ khác cho phép chương trình tự do lưu trữ giá trị. Giá trị tạo và lưu trên heap không bị giới hạn về kích thước mà chỉ phụ thuộc và kích thước RAM. Tuy nhiên tốc độ đọc ghi dữ liệu trên heap chậm hơn so với stack.

Để sử dụng heap, chương trình phải tự mình xin cấp phát và giải phóng bộ nhớ chiếm dụng trên heap. Nếu không sử dụng hợp lý vùng nhớ này có thể dẫn đến rò bộ nhớ (memory leak), vốn rất phổ biến khi lập trình C/C++.

.NET framework hỗ trợ rất tốt việc cấp phát và quản lý bộ nhớ của chương trình qua GC (Garbage Collector) nên người lập trình .NET không cần để ý nhiều đến việc xin cấp phát và giải phóng bộ nhớ heap.

Kiểu giá trị trong C#

Các biến kiểu giá trị có thể được gán một giá trị một cách trực tiếp, giá trị này được lưu trong bộ nhớ Stack. Chúng được kế thừa từ lớp System.ValueType.

Kiểu giá trị trực tiếp chứa dữ liệu. Một số ví dụ là int, char, và float, tương ứng giữ số nguyên, chữ cái, và số thực. Khi bạn khai báo một kiểu int, hệ thống cấp phát bộ nhớ để lưu giá trị đó.

Bảng sau liệt kê các kiểu giá trị có sẵn trong C# 2010:

Kiểu Biểu diễn Dãy giá trị Giá trị mặc định
bool Giá trị Boolean True hoặc False False
byte Kiểu unsigned integer (8 bit) 0 tới 255 0
char Kiểu Unicode character (16 bit) U +0000 tới U +ffff ‘\0’
decimal Kiểu thập phân (128 bit) (-7.9 x 1028 tới 7.9 x 1028) / 100 to 28 0.0M
double Kiểu double (64 bit) (+/-)5.0 x 10-324 tới (+/-)1.7 x 10308 0.0D
float Kiểu float (32 bit) -3.4 x 1038 tới + 3.4 x 1038 0.0F
int Kiểu integer (32 bit) -2,147,483,648 tới 2,147,483,647 0
long Kiểu signed integer (64 bit) -9,223,372,036,854,775,808 tới 9,223,372,036,854,775,807 0L
sbyte Kiểu signed integer (8 bit) -128 tới 127 0
short Kiểu signed integer (16 bit) -32,768 tới 32,767 0
uint Kiểu unsigned integer (32 bit) 0 tới 4,294,967,295 0
ulong Kiểu unsigned integer (64 bit) 0 tới 18,446,744,073,709,551,615 0
ushort Kiểu unsigned integer (16 bit) 0 tới 65,535 0

Từ khóa sizeof trong C#

Để lấy kích cỡ chính xác của một kiểu hoặc một biến trên một nền tảng cụ thể, bạn có thể sử dụng phương thức sizeof. Biểu thức sizeof(type) hiển thị kích cỡ của đối tượng hoặc kiểu bằng giá trị byte. Ví dụ dưới đây để lấy kích cỡ của kiểu int trên bất kỳ máy tính:

using System;

namespace DataTypeApplication 
{
   public class Program 
   {
      public static void Main(string[] args) 
      {
         Console.WriteLine("Size of int: {0}", sizeof(int));
         Console.ReadLine();
      }
   }
}
C#

Biên dịch và chạy chương trình C# trên sẽ cho kết quả sau:

Size of int: 4

Bạn có thể biên dịch và xem kết quả online tại đây.

Kiểu tham chiếu trong C#

Kiểu tham chiếu thì biến không chứa dữ liệu thực sự mà chúng chứa tham chiếu tới một vị trí bộ nhớ. Dữ liệu kiểu tham chiếu được lưu trong bộ nhớ Heap.

Việc sử dụng nhiều biến, thì kiểu tham chiếu có thể tham chiếu tới tới một vị trí bộ nhớ. Nếu dữ liệu trong vị trí bộ nhớ bị thay đổi bởi một trong số các biến, thì biến khác tự động phản ánh sự thay đổi về giá trị này. Ví dụ các kiểu tham chiếu có sẵn trong C# là: objectdynamic, và string.

Kiểu object trong C#

Kiểu object là lớp cơ sở cơ bản cho tất cả kiểu dữ liệu trong C# Common Type System (CTS). Object là một alias cho lớp System.Object. Các kiểu object có thể được gán giá trị của bất kỳ kiểu, kiểu giá trị, kiểu tham chiếu, kiểu tự định nghĩa (user-defined) khác. Tuy nhiên, trước khi gán các giá trị, nó cần một sự chuyển đổi kiểu.

Khi một kiểu giá trị được chuyển đổi thành kiểu object, nó được gọi là boxing và ngược lại, khi một kiểu object được chuyển đổi thành kiểu giá trị, nó được gọi là unboxing.

object obj;
obj = 100; // this is boxing
C#

Kiểu Dynamic trong C#

Bạn có thể lưu giữ bất kỳ kiểu giá trị nào trong biến kiểu dữ liệu dynamic. Việc kiểm tra các kiểu biến này diễn ra tại run time.

Cú pháp để khai báo một kiểu dynamic trong C# là:

dynamic <variable_name> = value;
C#

Ví dụ:

dynamic d = 20;
C#

Kiểu dynamic thì tương tự với kiểu object, ngoại trừ việc kiểm tra cho các biến kiểu object diễn ra tại thời điểm biên dịch (compile time), trong khi việc kiểm tra các biến kiểu dynamic diễn ra tại thời điểm thực thị (run time).

Kiểu string trong C#

Kiểu string trong C# cho phép bạn gán bất kỳ giá trị chuỗi nào cho một biến. Kiểu string là một alias cho lớp System.String. Nó kế thừa từ kiểu object. Giá trị cho một kiểu string có thể được gán bởi sử dụng các hằng chuỗi trong hai mẫu: quoted và @quoted.

Ví dụ:

string str = "Comdy";
C#

Và một hằng chuỗi @quoted trông như sau:

@"Comdy";
C#

Các kiểu tự định nghĩa (user-defined) trong C# là: Class, Interface, hoặc Delegate. Chúng ta sẽ bàn về các kiểu này trong các chương sau.

Các kiểu tự định nghĩa (user-defined) trong C# là: Class, Interface, hoặc Delegate. Chúng ta sẽ bàn về các kiểu này trong các chương sau.

Kiểu con trỏ trong C#

Các biến kiểu con trỏ lưu giữ địa chỉ bộ nhớ của kiểu khác. Các con trỏ trong C# có khả năng như con trỏ trong C hoặc C++.

Cú pháp để khai báo một kiểu con trỏ trong C# là:

type* identifier;
C#

Ví dụ:

char* cptr;
int* iptr;
C#

Chúng ta sẽ thảo luận về kiểu con trỏ ở chương: Unsafe Code trong C#.

Bạn có muốn xem bài viết tiếp theo không? Nó ở dưới đây nè.

36 thoughts on “Kiểu dữ liệu trong C#

  1. weight loss gummies reviews says:

    Someone actually help to make significantly articles I’d say This is the first time I frequented your website and up to now I’m impressed with the research you made to create this piece amazing Fantastic job.

  2. Tree Email says:

    I loved even more than you will get done right here. The picture is nice, and your writing is stylish, but you seem to be rushing through it, and I think you should give it again soon. I’ll probably do that again and again if you protect this walk.

  3. Suivre Téléphone says:

    Vous pouvez utiliser un logiciel de gestion des parents pour guider et surveiller le comportement des enfants sur Internet. Avec l’aide des 10 logiciels de gestion parentale les plus intelligents suivants, vous pouvez suivre l’historique des appels de votre enfant, l’historique de navigation, l’accès au contenu dangereux, les applications qu’il installe, etc.

  4. fake email address says:

    I wanted to take a moment to commend you on the outstanding quality of your blog. Your dedication to excellence is evident in every aspect of your writing. Truly impressive!

  5. youtube to mp3 320 says:

    My brother recommended I might like this web site He was totally right This post actually made my day You cannt imagine just how much time I had spent for this information Thanks

  6. kmtfirm says:

    Wonderful web site Lots of useful info here Im sending it to a few friends ans additionally sharing in delicious And obviously thanks to your effort

  7. etruesports says:

    I do not even know how I ended up here but I thought this post was great I dont know who you are but definitely youre going to a famous blogger if you arent already Cheers

  8. etruesports says:

    Wow superb blog layout How long have you been blogging for you make blogging look easy The overall look of your site is magnificent as well as the content

  9. Bacará móvel says:

    Alguém essencialmente deu uma mão para fazer artigos significativos. Id state Essa é a primeira vez que visitei a página do seu site e até agora fiquei surpreso com a pesquisa que você fez para tornar este envio real incrível Tarefa maravilhosa

  10. spacedaily says:

    Nem sei como vim parar aqui mas achei ótimo esse post não sei quem você é mas com certeza você está indo para um blogueiro famoso se ainda não o é.

  11. minihints says:

    Meu primo me recomendou este site, não tenho certeza se este post foi escrito por ele, pois ninguém mais sabe tão detalhadamente sobre minha dificuldade. Você é maravilhoso, obrigado

  12. kalorifer soba says:

    Your blog is a constant source of inspiration for me. Your passion for your subject matter shines through in every post, and it’s clear that you genuinely care about making a positive impact on your readers.

  13. kalorifer sobası says:

    Your writing is a true testament to your expertise and dedication to your craft. I’m continually impressed by the depth of your knowledge and the clarity of your explanations. Keep up the phenomenal work!

  14. top888casino says:

    Your blog is a testament to your passion for your subject matter. Your enthusiasm is infectious, and it’s clear that you put your heart and soul into every post. Keep up the fantastic work!

  15. temp mail says:

    I share your level of enthusiasm for the work you’ve produced. The sketch you’ve displayed is refined, and the material you’ve authored is impressive. Nevertheless, you seem anxious about the prospect of heading in a direction that could cause unease. I agree that you’ll be able to address this concern in a timely manner.

  16. temp mail says:

    I was just as enthralled by your work as you were. The visual presentation is refined, and the written content is sophisticated. However, you seem anxious about the possibility of presenting something that could be perceived as questionable. I believe you’ll be able to rectify this matter in a timely manner.

  17. trendaddictor says:

    Usually I do not read article on blogs however I would like to say that this writeup very compelled me to take a look at and do so Your writing taste has been amazed me Thanks quite nice post

  18. globesimregistration says:

    Your blog is a testament to your dedication to your craft. Your commitment to excellence is evident in every aspect of your writing. Thank you for being such a positive influence in the online community.

  19. theorangedip says:

    Hi Neat post There is a problem along with your website in internet explorer would test this IE still is the market chief and a good section of other folks will pass over your magnificent writing due to this problem

  20. igamingpro says:

    Usually I do not read article on blogs however I would like to say that this writeup very compelled me to take a look at and do it Your writing style has been amazed me Thank you very nice article

  21. globesimregistration says:

    you are in reality a good webmaster The website loading velocity is amazing It sort of feels that youre doing any distinctive trick Also The contents are masterwork you have done a fantastic job in this topic

  22. thedeadlines says:

    Nice blog here Also your site loads up very fast What host are you using Can I get your affiliate link to your host I wish my site loaded up as quickly as yours lol

  23. globesimregistration says:

    Your blog is a breath of fresh air in the often stagnant world of online content. Your thoughtful analysis and insightful commentary never fail to leave a lasting impression. Thank you for sharing your wisdom with us.

Leave a Reply

Your email address will not be published. Required fields are marked *