Cú pháp cơ bản của C#

C# là một ngôn ngữ lập trình hướng đối tượng. Trong phương pháp lập trình hướng đối tượng, một chương trình gồm các đối tượng tương tác với nhau bằng các hành động. Các hành động mà một đối tượng có thể thực hiện được gọi là các phương thức. Các đối tượng cùng loại được cho là có cùng kiểu hoặc được xem như là trong cùng lớp.

Ví dụ, xét đối tượng Rectangle. Nó có các thuộc tính như length và width. Tùy thuộc vào thiết kế, nó có thể cần cập nhật các giá trị của thuộc tính này, tính toán diện tích và hiển thị chi tiết.

Bạn theo dõi ví dụ sau triển khai một lớp Rectangle và cú pháp C# cơ bản của chương trình này. Để minh họa rõ ràng tính hướng đối tượng của C#, mình sẽ tạo hai class trong hai file riêng rẽ nhau.

Lớp Rectangle: chứa các thuộc tính, phương thức chính:

using System;

namespace RectangleApplication 
{
   class Program 
   {
      static void Main(string[] args) 
      {
         Rectangle r = new Rectangle();
         r.Acceptdetails();
         r.Display();
         Console.ReadLine(); 
      }
   }
	
   class Rectangle 
   {      
      // member variables
      double length;
      double width;
      
      public void Acceptdetails() 
      {
         length = 4.5;    
         width = 3.5;
      }
      public double GetArea() 
      {
         return length * width; 
      }
      public void Display() 
      {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }
}
C#

Khi đoạn mã trên được biên dịch và thực thi, nó tạo ra kết quả sau:

Length: 4.5
Width: 3.5
Area: 15.75

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

Từ khóa using trong C#

Lệnh đầu tiên trong bất kỳ chương trình C# nào là:

using System;
C#

Từ khóa using được sử dụng để khai báo sử dụng thư viện trong chương trình. Như ở ví dụ trên là khai báo sử dụng thư viện System. Một chương trình C# có thể bao nhiều lệnh using.

Từ khóa class trong C#

Từ khóa class được sử dụng để khai báo một lớp trong C#.

Comment trong C#

Comment được sử dụng để ghi chú cho code. Compiler bỏ qua các comment. Các comment đa dòng trong các chương trình C# bắt đầu với /* và kết thúc với */ như sau:

/* This program demonstrates
The basic syntax of C# programming 
Language */
C#

Comment trên một dòng được bắt đầu bằng ký hiệu //. Ví dụ:

//end class Rectangle  
C#

Biến trong C#

Biến là các thành phần của một lớp, được sử dụng để lưu trữ dữ liệu. Trong chương trình trên, lớp Rectangle có hai biến là length và width.

Phương thức trong C#

Phương thức là tập hợp của nhiều lệnh để thực hiện một tác vụ cụ thể nào đó. Các phương thức của một lớp được khai báo bên trong lớp đó. Lớp Rectangle chứa 3 phương thức là: AcceptDetailsGetArea và Display.

Thuyết minh một Class trong C#

Trong chương trình trên, lớp ExecuteRectangle chứa phương thức Main() và khởi tạo lớp Rectangle.

Định danh (Identifier) trong C#

Một định danh là một tên được sử dụng để nhận diện một lớp, biến, thuộc tính, phương thức hoặc bất kỳ thành phần tự định nghĩa nào (user-defined).

  • Một tên phải bắt đầu với một chữ cái mà có thể được theo sau bởi một dãy các chữ cái, chữ số (0-9) hoặc dấu gạch dưới (_). Ký tự đầu tiên của một định danh không thể là một chữ số.
  • Nó không chứa bất kỳ khoảng trống hoặc ký tự như ? – + ! @ # % ^ & * ( ) [ ] { } . ; : ” ‘ / và \. Tuy nhiên, dấu gạch dưới có thể được sử dụng.
  • Nó không được trùng với một từ khóa trong C#.

Từ khóa trong C#

Từ khóa là các từ dành riêng (Reserved Keyword) được định nghĩa trước cho trình biên dịch C#. Những từ khóa này không thể được sử dụng làm định danh. Tuy nhiên, nếu bạn muốn sử dụng các từ khóa này để làm định danh, bạn có thể đặt ký tự @ ở trước chúng.

Trong C#, một số định danh có ý nghĩa đặc biệt trong ngữ cảnh của code, ví dụ như get và set được gọi là từ khóa theo ngữ cảnh (contextual keyword).

Bảng sau liệt kê các từ khóa dành riêng và các từ khóa theo ngữ cảnh trong C#:

Từ khóa dành riêng
abstract as base bool break byte case
catch char checked class const continue decimal
default delegate do double else enum event
explicit extern false finally fixed float for
foreach goto if implicit in in (generic modifier) int
interface internal is lock long namespace new
null object operator out out (generic modifier) override params
private protected public readonly ref return sbyte
sealed short sizeof stackalloc static string struct
switch this throw true try typeof uint
ulong unchecked unsafe ushort using virtual void
volatile while
Từ khóa theo ngữ cảnh
add alias ascending descending dynamic from get
global group into join let orderby partial (type)
partial
(method)
remove select set

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

40 thoughts on “Cú pháp cơ bản của C#

  1. Health Stay says:

    I’m often to blogging and i really appreciate your content. The article has actually peaks my interest. I’m going to bookmark your web site and maintain checking for brand spanking new information.

  2. Tree Mail says:

    helloI like your writing very so much proportion we keep up a correspondence extra approximately your post on AOL I need an expert in this space to unravel my problem May be that is you Taking a look forward to see you

  3. Phone Tracker Free says:

    You can use parent management software to guide and supervise children’s behavior on the Internet. With the help of the following 10 smartest parent management software, you can track your child’s call history, browsing history, dangerous content access, apps they install, 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. binance says:

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  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. floatswitchs 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

  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. 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

  20. 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 *