반응형
C#(C-Sharp)
- MS가 개발한 객체지향 프로그래밍 언어
- .NET 프레임워크와 함께 사용되며, 윈도우, 웹, 모바일, 클라우드 기반 등 다양한 플랫폼에서 실행되는 소프트웨어를 개발할 수 있도록 설계됨
- JAVA와 유사한 문법을 갖고 있음
주요 특징
- 객체지향(OOP) 언어 : 클래스와 객체를 중심으로 프로그램 작성
- 타입 안전성(Type Safety) : 컴파일 시간에 타입 오류를 잡을 수 있음
- 메모리 관리 : Garbage Collection을 통해 자동으로 메모리를 관리
- 다양한 플랫폼 지원 : .Net Core와 Xamarin 등을 통해 Windows, Linux, macOS, iOS, Android 등 다양한 플랫폼에서 실행되는 애플리케이션을 만들 수 있음
- 언어 통합 쿼리(LINQ) : 데이터 쿼리를 객체지향 방식으로 처리할 수 있도록 LINQ 제공
- 비동기 프로그래밍 : async와 await 키워드를 통해 비동기 작업을 쉽게 처리할 수 있음
문법
1. 데이터 타입(Data Types)
- JAVA와 나머지 기본 타입 비슷
- JAVA에서는 boolean, C#에서는 bool 사용
JAVA :
boolean isActive = true;
C# :
bool isActive = true;
2. 클래스(Class)
- JAVA에서와 동일하게 class 키워드를 사용
- 클래스 내의 변수와 메소드에 접근 제어자를 지정해 주어야 함 -> 자바에서처럼 default 접근 제어자가 자동으로 적용되지 않음
- 접근 제어자를 지정하지 않으면 컴파일 오류 발생
JAVA :
class Car {
String color;
void start() {
System.out.println("Car is starting");
}
}
C# :
class Car {
public string color;
public void Start() {
Console.WriteLine("Car is starting");
}
}
실습 :
using System;
class Car {
public string color;
public void Start() {
Console.WriteLine("Car is starting");
}
}
class Program {
static void Main(String[] args) {
Car myCar = new Car();
myCar.color = "Red";
myCar.Start();
Console.WriteLine("Car color : " + myCar.color);
}
}
3. 인터페이스(Interface)
- JAVA와 비슷하게, 인터페이스는 구현을 강제하는 메소드의 집합
- C#에서는 인터페이스 이름에 I를 붙이는 것이 관습임
JAVA :
interface Vehicle {
void Start();
}
class Car implements Vehicle {
public void Start() {
System.out.println("Car is starting");
}
}
C# :
interface IVehicle {
void Start();
}
class Car : IVehicle {
public void Start() {
Console.WriteLine("Car is starting");
}
}
실습 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 {
interface IVehicle {
void Start();
}
class Car : IVehicle {
public void Start() {
Console.WriteLine("Car is starting");
}
}
class Program {
static void Main(string[] args) {
IVehicle myCar = new Car();
myCar.Start();
}
}
}
4. 상속(Inheritance)
- : base 키워드를 사용하여 부모 클래스 지정
- 부모 클래스는 base 클래스, 자식 클래스는 derived 클래스라고 함
- virtual : 메소드 오버라이딩을 허용한다는 의미
- C#에서는 virtual 키워드를 사용해 부모 클래스에서 오버라이딩을 허용하는 메소드를 선언하고, 자식 클래스에서는 override 키워드로 메소드를 오버라이딩 함
- JAVA에서는 @Override 어노테이션을 사용하여 메소드 오버라이딩을 명시함
JAVA :
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}
C# :
class Animal {
public virtual void Sound() {
Console.WriteLine("Some sound");
}
}
class Dog : Animal {
public override void Sound() {
Console.WriteLine("Bark");
}
실습 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 {
class Animal {
public virtual void Sound() {
Console.WriteLine("Some sound");
}
}
class Dog : Animal {
public override void Sound() {
Console.WriteLine("Bark");
}
static void Main(string[] args) {
Animal animal = new Dog();
animal.Sound();
}
}
}
5. 조건문(If-Else Statement)
- 문법이 같음
6. 반복문(Looping)
- 문법이 같음
7. 생성자(Constructor)
- 문법이 같음
- C#에서는 생성자에 접근 제어자를 명시적으로 작성해 주어야 함
JAVA :
class Car {
String model;
//생성자
Car(String model) {
this.model = model;
}
}
C# :
class Car {
public string model;
//생성자
public Car(string model) {
this.model = model;
}
}
8. 프로퍼티(Property)
- C#에서는 멤버 변수에 대한 접근을 직접 제공하는 대신, 프로퍼티를 사용하는 것이 일반적
- C#에서는 get과 set을 통해 멤버 변수에 접근할 수 있는 프로퍼티를 정의할 수 있음
- JAVA에서는 직접 메소드를 사용해 접근
- 객체의 필드를 읽고 수정할 수 있는 것 -> get과 set 블록을 사용하여 값을 가져오거나 설정할 수 있음
- JAVA에서의 getter, setter와 같은 개념이지만, C#에서는 프로퍼티를 사용하면 자동으로 get이나 set이 호출됨 -> 아래 예시에서 myCar.Model이 읽기인 경우 get이 호출되고, 쓰기일 경우 set이 호출됨
JAVA :
class Car {
private String model; //private 필드
//getter 메소드
public String getModel() {
return model;
}
//setter 메소드
public void setModel(String model) {
this.model = model;
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.setModel("Tesla"); //setter를 사용하여 값을 설정
System.out.println(myCar.getModel()); //getter를 사용하여 값 출력
}
}
C# :
namespace ConsoleApp1 {
class Car {
private string model; //private 필드
//프로퍼티 정의
public string Model {
get { return model; } //값을 가져오는 get
set { model = value; } //값을 설정하는 set
}
}
}
using ConsoleApp1;
class Program {
static void Main() {
Car myCar = new Car();
myCar.Model = "Tesla"; //set을 사용하여 값을 설정
Console.WriteLine(myCar.Model); //get을 사용하여 값을 출력
}
}
9. 예외 처리 구문(Exceptin Handling Syntax)
- JAVA와 C# 모두 예외 처리의 기본적인 구조는 거의 같음(두 언어 모두 try, catch, finally 구문을 사용하여 예외 처리)
- 예외 클래스는 언어마다 다름
- JAVA에서는 산술 오류를 처리할 때 ArithmeticException 사용
- C#에서는 DivideByZeroException(System namespace에 포함되어 있음)을 사용하여 0으로 나누는 오류를 처리
JAVA :
try {
int result = 10 / 0; //ArithmeticException 발생
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero"); //예외 처리
} finally {
System.out.println("Finally block executed");
}
C# :
try {
int result = 10 / 0; //DivideByZeroException 발생
} catch (DivideByZeroException e) {
Console.WriteLine("Cannot divide by zero"); //예외 처리
} finally {
Console.WriteLine("Finally block executed");
}
반응형