Convert.ToInt32() vs Int32.Parse() vs Int32.TryParse()

http://www.codeproject.com/KB/cs/AgileWare_Convert_Int32.aspx

Convert.ToInt32(string s)는 내부적으로 Int32.Parse(string s)을 불러서 string을 32-bit signed integer로 변환시켜주는 메소드

string s1 = 1234″;
string s2 = 1234.65″;
string s3 = null;
string s4 = 123456789123456789123456789123456789123456789″; 
intresult;
bool success; result = Convert.ToInt32(s1); //— 1234
result = Convert.ToInt32(s2); //— FormatException 
result = Convert.ToInt32(s3); //— 0 
result = Convert.ToInt32(s4); //— OverflowException

Int32.Parse(string s)는 strng을 32-bit signed integer로 변환시켜주는 메소드
그러나 만약 s가 null일 경우 ArgumentNullException을 냄
또한 s가 integer가 아닐 경우 FormatException을 냄
또한 s가 integer의 MinValue또는 MaxVale를 넘칠 경우 OverflowException을 냄

result = Int32.Parse(s1); //— 1234 
result = Int32.Parse(s2); //— FormatException 
result = Int32.Parse(s3); //— ArgumentNullException 
result = Int32.Parse(s4); //— OverflowException



Int32.TryParse(string s, out int i)는 string을 32-bit signed integer로 변환하여 out 에 보내주는 메소드로 성공하면 true를 반환
따라서 만약 s가 null일 경우 ArgumentNullException을 내지않고 false와 out으로 0을 반환
또한 s가 integer가 아닐 경우 FormatException을 내지않고 false와 out으로 0을 반환
또한 s가 integer의 MinValue또는 MaxVale를 넘칠 경우 OverflowException을 내지않고 false와 out으로 0을 반환

success = Int32.TryParse(s1, out result); //— success => true; result => 1234 
success = Int32.TryParse(s2, out result); //— success => false; result => 0 
success = Int32.TryParse(s3, out result); //— success => false; result => 0 
success = Int32.TryParse(s4, out result); //— success => false; result => 0

C# Formatting Numeric String

Formatting Standard Numeric Format Strings http://msdn.microsoft.com/en-us/library/s8s7t687(VS.80).aspx

Formatting Custom Numeric Format Strings http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Formatting Numeric Format Strings (Alignment)
-Integer http://www.csharp-examples.net/string-format-int/
-Double http://www.csharp-examples.net/string-format-double/
-DateTime http://www.csharp-examples.net/string-format-datetime/
-Align String with Spaces http://www.csharp-examples.net/align-string-with-spaces/
-Indent String with Spaces http://www.csharp-examples.net/indent-string-with-spaces/
-IFormatProvider http://www.csharp-examples.net/iformatprovider-numbers/
-Custom IFormatProvider http://www.csharp-examples.net/custom-iformatprovider/

String.Substring Method

http://msdn.microsoft.com/ko-kr/library/system.string.aspx

Substring(Int32) 이 인스턴스에서 부분 문자열을 검색합니다. 부분 문자열은 지정된 문자 위치에서 시작됩니다.

Substring(Int32, Int32) 이 인스턴스에서 부분 문자열을 검색합니다. 부분 문자열은 지정된 문자 위치에서 시작하고 길이도 지정되어 있습니다.

string str = “Hi, Welcome to HCI Programming II! Hi”;
Console.WriteLine(“str의 substring(3) {0}”, str.Substring(3)); // ” Welcome to HCI Programming II! Hi” 3번째 위치에서 떼어냄

Console.WriteLine(“str의 substring(14, 20) {0}”, str.Substring(14,20)); // ” HCI Programming II!” 14번째 위치에서부터 20개 만큼 떼어냄

Console Class

http://msdn.microsoft.com/en-us/library/system.console.aspx

Console 클래스에는 ReadLine, WriteLine 같은 기본적인 입출력 메서드 외에도 콘솔 관리를 위한 여러 가지 멤버들이 제공된다. 어떤 멤버는
함수처럼 필요할 때 호출할 수 있는 메서드이고 어떤 것은 값을 읽고 쓰는 프로퍼티 형태로 되어 있다.

멤버

설명

Title

콘솔창의
제목
문자열이다.

BackgroundColor, ForegroundColor

전경색, 배경색의
색상이다.

CursorSize

커서의
높이를
지정한다.

CursorVisible

커서의
보임/숨김을
지정한다.

CursorLeft, CursorTop

커서의
현재
위치이다.

Clear()

화면을
지운다.

Beep()


소리를
낸다.

ResetColor()

디폴트
색상으로
변경한다.

SetCursorPosition(x,y)

커서의
위치를
옮긴다.

class Program
{
public
static void Main()
{
        Console.Title = “콘솔 테스트”; // 콘솔창의 제목
        Console.BackgroundColor = ConsoleColor.Blue; // 콘솔창의 배경색
Console.ForegroundColor = ConsoleColor.Yellow; // 콘솔창의 전경색
        Console.Clear(); // 콘솔창 화면을 깨끗이 지움
Console.Beep(); // 콘솔창에 삑소리를 냄
Console.WriteLine(“색상을 변경했습니다.”); // 콘솔창에 “색상을 변경했습니다.” 출력
Console.ReadKey(); // 콘솔창에서 아무키나 입력받길 대기
Console.ResetColor(); // 콘솔창에서 색상(배경,전경)을 초기화
        Console.SetCursorPosition(10, 10); // (10, 10) 좌표로 커서를 이동
Console.WriteLine(“디폴트 색상입니다.”); //  콘솔창에 “디폴트 색상입니다.” 출력
Console.ReadKey(); // 콘솔창에서 아무키나 입력받길 대기
    }
}

Stack vs Heap

스택(Stack)은 Last-In, First-Out(LIFO) 방식으로 아이템을 저장하는 메모리의 자료 구조이다.
스택(Stack)은 지역변수(local variable)와 함수 리턴주소를 저장한다. C#에서 값형식(Value Type) 데이터는 스택에 저장된다.

힙(Heap)은 프로그램 코드 영역과는 별도로 유지되는 자유 메모리 공간이다.
힙(Heap)은 C#에서 new를 사용하여 메모리 할당하여 이 공간을 사용할 수 있다.
힙에 할당된 데이터는 전역변수(global variable)처럼 프로그램이 종료될 때까지 유지된다.
C#에서는 더이상 참조하지 않는 데이터를 자동으로 해제해준다 (gabage collection).
C#에서는 참조형식(Reference Type)은 스택에 메모리 주소를 저장하고 힙에 실질적인 데이터가 저장된다.

http://en.csharp-online.net/Stack_vs._Heap

http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap

Value Type vs Reference Type

구분 값 형식(Value Type) 참조 형식(Reference Type)
종류 내장형 (int, char, float,…)사용자 정의형 (enum, stuct) Object, string, class, interface, delegate, ..
메모리 사용 스택 스택, 힙
대입(Assignment) 복사 참조 변경
크기 고정 가변
Garbage Collector 지원 지원 안됨 지원 됨

값형식(Value Type)은 메모리를 직접 가리킨다. 참조형식(Reference Type)은 메모리를 참조를 통해서 가리킨다.

값형식(Value Type)은 변수의 선언과 동시에 메모리에 생성한다. 참조형식(Reference Type)은 변수의 선언과 메모리 생성 분리하여 생성한다.

값형식(Value Type)은 값형식끼리 할당 할 때 메모리의 값들을 그대로 복사한다.

참조형식(Reference Type)은 참조형식끼리 할당 할때 참조값만을 복사한다.

http://dis.dankook.ac.kr/lectures/hci10/entry/Value-Type과-Reference-Type의-비교

C# Struct

C++에서는 struct와 class간에 차이가 거의 없으며, 차이점은 아무런 명시를 하지 않았을 때 class는 멤버가 private 권한을 가지고, struct는 멤버가 public 권한을 가진다.

C#에서는 struct와 class가 유사하나 매우 다른 특징을 가진다.
-C# struct는 Value Type (값 형식)으로, 즉 stack영역에 데이터를 생성해서 사용함
-C# struct는 Default Constructor (기본생성자)나 Destructor(소멸자)선언할 수 없음
-C# struct는 다른 struct/class를 상속받을 수 없으며 파생시킬수도 없음 (따라서, protected는 선언할 수 없음)
-C# struct는 interface를 구현할 수 있음
-C# struct는 nullable type으로 사용할 수 있음
-C# struct는 일반적으로 new를 사용해서 객체를 생성하나 (예: Person p = new Person();),
stack영역에 데이터를 생성해서 사용함

public struct Point
{
int x = 1; //Illegal: cannot initialize field
int y;

public Point() { } //Illegal: cannot have parameterless constructor
public Point(int x) { this.x = x; } //Illegal: must assign field y
}
http://www.codeproject.com/Articles/8612/Structs-in-C

C# Data Type

Boolean (bool) BoolType.cs

Character (char) CharType.cs

Enumeration (enum) EnumType.cs

Numeric (int, long, float, double, decimal, etc) NumericType.cs

String StringType.cs

Object ObjectType.cs

Struct StructType.cs
StructTest StructTest.cs

Array ArrayTest.cs

int, float, double, char, bool http://www.hoons.kr/Lecture/LectureMain.aspx?BoardIdx=151&kind=4&view=0

enum, struct http://csharpstudy.com/CSharp/CSharp-struct.aspx

String http://www.hoons.kr/Lecture/LectureMain.aspx?BoardIdx=48205&kind=53&view=0

System.Object http://www.hoons.kr/Lecture/LectureMain.aspx?BoardIdx=155&kind=4&view=0

Generics (C# 2.0) http://www.hoons.kr/Lecture/LectureMain.aspx?BoardIdx=153&kind=4&view=0

Nullable (C# 2.0) http://csharpstudy.com/CSharp/CSharp-datatype.aspx

var (implicit type) (C# 3.0) http://msdn.microsoft.com/ko-kr/library/bb383973.aspx

.Net Namespace

using System;

namespace ConsoleApplication1
{
  namespace A
{
class MyClass
{
int value = 1;
public void MyMethod() { System.Console.WriteLine(value); }
}
}
  namespace B
{
class MyClass
{
double value = 2.1;
public void MyMethod() { System.Console.WriteLine(value); }
}
}

class Program
{
static void Main(string[] args)
{

        A.MyClass a = new A.MyClass();
a.MyMethod(); // 1 출력
        B.MyClass b = new B.MyClass();
b.MyMethod(); // 2.1 출력
}
}
}

namespace SampleNamespace
{
class SampleClass
{
public void SampleMethod()
{
System.Console.WriteLine(
“SampleMethod inside SampleNamespace”);
}
}// Create a nested namespace, and define another class.
namespace NestedNamespace
{
class SampleClass
{
public void SampleMethod()
{
System.Console.WriteLine(
“SampleMethod inside NestedNamespace”);
}
}
}

class Program
{
static void Main(string[] args)
{
// Displays “SampleMethod inside SampleNamespace.”
SampleClass outer = new SampleClass();
outer.SampleMethod();

// Displays “SampleMethod inside SampleNamespace.”
SampleNamespace.SampleClass outer2 = new SampleNamespace.SampleClass();
outer2.SampleMethod();

// Displays “SampleMethod inside NestedNamespace.”
NestedNamespace.SampleClass inner = new NestedNamespace.SampleClass();
inner.SampleMethod();
}
}
}