Saturday 29 October 2016

24. Exception Handling C# (Basic/Dasar)

Exception adalah sebuah masalah yang muncul ketika program dijalankan, ada banyak faktor yang menyebabkan terjadinya masalah tersebut. Dengan adanya masalah yang timbul tesebut perlu adanya penganganan exception tersebut.

Exception memberikan kemudahan kepada kita untuk mengatur dan menangani masalah yang muncul saat program dijalankan. Untuk menangani exceptions pada C# kita bisa menggunakan keyword try, catch, finally and throw.

  • try: adalah blok kode yang digunakan untuk melakukan pengetesan apakah pada blok kode tersebut ada masalah atau tidak. Try akan selalu diikuti dengan satu atau lebih blok catch.
  • catch: adalah blok yang digunakan untuk menangani jika pada pengetesan blok try terjadi kesalahan pada kode. Kemudian kita bisa melakukan penanganan kesalahan yang terjadi pada blok catch.
  • finally: adalah blok yang akan selalu dieksekusi setelah blok try dan catch selesai dieksekusi.
  • thrown: adalah blok yang digunakan untuk melaporkan jika terjadi kesalahan pada blok kode, blok thrown biasanya berdiri sendiri dan terpisah dari try, catch dan finally.
Syntax untuk exception handling adalah sebagai berikut:

try
{
   // statements causing exception
}
catch( ExceptionName e1 )
{
   // error handling code
}
catch( ExceptionName e2 )
{
   // error handling code
}
catch( ExceptionName eN )
{
   // error handling code
}
finally
{
   // statements to be executed
}

Berdasarkan syntax diatas kita bisa menangani kesalahan berdasarkan exception yang berbeda beda menggunakan multiple catch.

Exception Classes pada C#

Pada C# exception akan ditangani oleh class System.Exception, System.ApplicationException dan System.SystemException.

Tabel berikut ini adalah beberapa class untuk menangani exception pada C#

Exception ClassDescription
System.IO.IOExceptionHandles I/O errors.
System.IndexOutOfRangeExceptionHandles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchExceptionHandles errors generated when type is mismatched with the array type.
System.NullReferenceExceptionHandles errors generated from deferencing a null object.
System.DivideByZeroExceptionHandles errors generated from dividing a dividend with zero.
System.InvalidCastExceptionHandles errors generated during typecasting.
System.OutOfMemoryExceptionHandles errors generated from insufficient free memory.
System.StackOverflowExceptionHandles errors generated from stack overflow.
Menangani Exception

Untuk mengani exception kita bisa menggunakan try, catch dan finally blok. Yang paling penting adalah penggunaan try - catch blok sedangkan untuk finally blok adalah optional.

Berikut ini adalah contoh program untuk mengiliustrasikan penanganan exception:

using System;
namespace ErrorHandlingApplication
{
   class DivNumbers
   {
      int result;
      DivNumbers()
      {
         result = 0;
      }
      public void division(int num1, int num2)
      {
         try
         {
            result = num1 / num2;
         }
         catch (DivideByZeroException e)
         {
            Console.WriteLine("Exception caught: {0}", e);
         }
         finally
         {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args)
      {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}

Contoh di atas adalah untuk mengani kesalah jika terjadi pembagian dengan 0, setelah program dijalankan maka akan memberikan keluaran sebagai berikut:

Exception caught: System.DivideByZeroException: Attempted to divide by zero. 
at ...
Result: 0

Kita juga bisa mendefinisikan exception kita sendiri, Untuk membuat exception kita bisa menggunakan class Exception. Contoh program dibawah ini akan mengilustrasikan bagaimana custom exception dibuat:

using System;
namespace UserDefinedException
{
   class TestTemperature
   {
      static void Main(string[] args)
      {
         Temperature temp = new Temperature();
         try
         {
            temp.showTemp();
         }
         catch(TempIsZeroException e)
         {
            Console.WriteLine("TempIsZeroException: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}

public class TempIsZeroException: Exception
{
   public TempIsZeroException(string message): base(message)
   {
   }
}

public class Temperature
{
   int temperature = 0;
   public void showTemp()
   {
      if(temperature == 0)
      {
         throw (new TempIsZeroException("Zero Temperature found"));
      }
      else
      {
         Console.WriteLine("Temperature: {0}", temperature);
      }
   }
}

Contoh program diatas akan melakukan pengecekan jika nilai temperature bernilai 0 maka akan mengahsilkan TemperatureException.

Setelah program dijalankan akan memberikan output sebagai berikut:

TempIsZeroException: Zero Temperature found

Ok guys, sampai disini dulu dan sampai ketemu di tutorial selanjutnya File/IO.

Wednesday 26 October 2016

23. Regular Expressions

Helo guys, kali ini saya akan membahas Regular Expressions salah satu menu favorit saya dalam dunia permrograman. Karena sudah banyak project saya kerjakan dengan menggunakan metode ini untuk parsing dan ekstraksi data.

Regular expression adalah metode untuk mencocokkan sebuah pola/pattern dari sebuah text. Dalam .Net framework mempunyai regular expression engine yang dapat digunakan untuk melakukan pencocokan dan ekstraksi text sesuai dengan pola/pattern yang kita inginkan.

Membuat dan Mendefinisikan Regular Expressions

Ada beberapa kombinasi dalam membuat sebuah pola/pattern pada regular expressions yaitu berupa karakter dan operator.

1. Character Escape

Merupakan spesial karakter yang digunakan untuk menyatakan sebuah ekpresi filtering, berikut adalah daftar tabel untuk character escape:

Escape characterDescriptionPatternMatches
\aMatches a bell character, \u0007.\a"\u0007" in "Warning!" + '\u0007'
\bIn a character class, matches a backspace, \u0008.[\b]{3,}"\b\b\b\b" in "\b\b\b\b"
\tMatches a tab, \u0009.(\w+)\t"Name\t", "Addr\t" in "Name\tAddr\t"
\rMatches a carriage return, \u000D. (\r is not equivalent to the newline character, \n.)\r\n(\w+)"\r\nHello" in "\r\Hello\nWorld."
\vMatches a vertical tab, \u000B.[\v]{2,}"\v\v\v" in "\v\v\v"
\fMatches a form feed, \u000C.[\f]{2,}"\f\f\f" in "\f\f\f"
\nMatches a new line, \u000A.\r\n(\w+)"\r\nHello" in "\r\Hello\nWorld."
\eMatches an escape, \u001B.\e"\x001B" in "\x001B"
\nnnUses octal representation to specify a character (nnn consists of up to three digits).\w\040\w"a b", "c d" in "a bc d"
\x nnUses hexadecimal representation to specify a character (nn consists of exactly two digits).\w\x20\w"a b", "c d" in "a bc d"
\c X\c xMatches the ASCII control character that is specified by X or x, where X or x is the letter of the control character.\cC"\x0003" in "\x0003" (Ctrl-C)
\u nnnnMatches a Unicode character by using hexadecimal representation (exactly four digits, as represented by nnnn).\w\u0020\w"a b", "c d" in "a bc d"
\When followed by a character that is not recognized as an escaped character, matches that character. \d+[\+-x\*]\d+\d+[\+-x\*\d+"2+2" and "3*9" in "(2+2) * 3*9"
2. Character Classes

Character classes digunakan untuk menyatakan seabuah set atau sekumpulan dari character. Berikut ini adalah character classes:

Character classDescriptionPatternMatches
[character_group]Matches any single character in character_group. By default, the match is case-sensitive.[mn]"m" in "mat" "m", "n" in "moon"
[^character_group]Negation: Matches any single character that is not in character_group. By default, characters incharacter_group are case-sensitive.[^aei]"v", "l" in "avail"
[ first - last ]Character range: Matches any single character in the range from first to last.[b-d][b-d]irds Birds Cirds Dirds
.Wildcard: Matches any single character except \n.a.e"ave" in "have" "ate" in "mate"
\p{ name }Matches any single character in the Unicode general category or named block specified by name.\p{Lu}"C", "L" in "City Lights"
\P{ name }Matches any single character that is not in the Unicode general category or named block specified by name.\P{Lu}"i", "t", "y" in "City"
\wMatches any word character.\w"R", "o", "m" and "1" in "Room#1"
\WMatches any non-word character.\W"#" in "Room#1"
\sMatches any white-space character.\w\s"D " in "ID A1.3"
\SMatches any non-white-space character.\s\S" _" in "int __ctr"
\dMatches any decimal digit.\d"4" in "4 = IV"
\DMatches any character other than a decimal digit.\D" ", "=", " ", "I", "V" in "4 = IV"
3. Anchor

Anchor digunakan untuk mencocokkan pola/pattern berdasarkan posisi character saat ini. Berikut ini adalah anchor pada Regular Expressions.

AssertionDescriptionPatternMatches
^The match must start at the beginning of the string or line.^\d{3}"567" in "567-777-"
$The match must occur at the end of the string or before \nat the end of the line or string.-\d{4}$"-2012" in "8-12-2012"
\AThe match must occur at the start of the string.\A\w{3}"Code" in "Code-007-"
\ZThe match must occur at the end of the string or before \n at the end of the string.-\d{3}\Z"-007" in "Bond-901-007"
\zThe match must occur at the end of the string.-\d{3}\z"-333" in "-901-333"
\GThe match must occur at the point where the previous match ended.\\G\(\d\)"(1)", "(3)", "(5)" in "(1)(3)(5)[7](9)"
\bThe match must occur on a boundary between a \w(alphanumeric) and a \W(nonalphanumeric) character.\w"R", "o", "m" and "1" in "Room#1"
\BThe match must not occur on a \b boundary.\Bend\w*\b"ends", "ender" in "end sends endure lender"
4. Grouping Constructs

Merupakan pencocokan berdasarkan set group dari character atau substring. Berikut ini adalah daftar grouping constructs.

Grouping constructDescriptionPatternMatches
( subexpression )Captures the matched subexpression and assigns it a zero-based ordinal number.(\w)\1"ee" in "deep"
(?< name >subexpression)Captures the matched subexpression into a named group.(?< double>\w)\k< double>"ee" in "deep"
(?< name1 -name2 >subexpression)Defines a balancing group definition.(((?'Open'\()[^\(\)]*)+((?'Close-Open'\))[^\(\)]*)+)*(?(Open)(?!))$"((1-3)*(3-1))" in "3+2^((1-3)*(3-1))"
(?: subexpression)Defines a noncapturing group.Write(?:Line)?"WriteLine" in "Console.WriteLine()"
(?imnsx-imnsx:subexpression)Applies or disables the specified options within subexpression.A\d{2}(?i:\w+)\b"A12xl", "A12XL" in "A12xl A12XL a12xl"
(?= subexpression)Zero-width positive lookahead assertion.\w+(?=\.)"is", "ran", and "out" in "He is. The dog ran. The sun is out."
(?! subexpression)Zero-width negative lookahead assertion.\b(?!un)\w+\b"sure", "used" in "unsure sure unity used"
(?< =subexpression)Zero-width positive lookbehind assertion.(?< =19)\d{2}\b"51", "03" in "1851 1999 1950 1905 2003"
(?< ! subexpression)Zero-width negative lookbehind assertion.(?< !19)\d{2}\b"ends", "ender" in "end sends endure lender"
(?> subexpression)Nonbacktracking (or "greedy") subexpression.[13579](?>A+B+)"1ABB", "3ABB", and "5AB" in "1ABB 3ABBC 5AB 5AC"
5. Quantifiers

Quantifiers menyatakan berapa banyak element (character, group atau character classes) yang muncul  pada sebuah string/text.

QuantifierDescriptionPatternMatches
*Matches the previous element zero or more times.\d*\.\d".0", "19.9", "219.9"
+Matches the previous element one or more times."be+""bee" in "been", "be" in "bent"
?Matches the previous element zero or one time."rai?n""ran", "rain"
{ n }Matches the previous element exactly n times.",\d{3}"",043" in "1,043.6", ",876", ",543", and ",210" in "9,876,543,210"
{ n ,}Matches the previous element at least n times."\d{2,}""166", "29", "1930"
{ n , m }Matches the previous element at least n times, but no more than m times."\d{3,5}""166", "17668" "19302" in "193024"
*?Matches the previous element zero or more times, but as few times as possible.\d*?\.\d".0", "19.9", "219.9"
+?Matches the previous element one or more times, but as few times as possible."be+?""be" in "been", "be" in "bent"
??Matches the previous element zero or one time, but as few times as possible."rai??n""ran", "rain"
{ n }?Matches the preceding element exactly n times.",\d{3}?"",043" in "1,043.6", ",876", ",543", and ",210" in "9,876,543,210"
{ n ,}?Matches the previous element at least n times, but as few times as possible."\d{2,}?""166", "29", "1930"
{ n , m }?Matches the previous element between n and m times, but as few times as possible."\d{3,5}?""166", "17668" "193", "024" in "193024"
6. Backreference Constructs

Digunanakan untuk mencocokkan urutan sub expression pada sebuah regular expressions yang sama.

Backreference constructDescriptionPatternMatches
\ numberBackreference. Matches the value of a numbered subexpression.(\w)\1"ee" in "seek"
\k< name >Named backreference. Matches the value of a named expression.(?< char>\w)\k< char>"ee" in "seek"
7. Alternation Constructs

Digunakan untuk mencocokkan beberapa pattern, sehingga pencocokan mempunyai beberapa alternatif.

Alternation constructDescriptionPatternMatches
|Matches any one element separated by the vertical bar (|) character.th(e|is|at)"the", "this" in "this is the day. "
(?( expression )yes | no )Matches yes if expression matches; otherwise, matches the optional no part. Expression is interpreted as a zero-width assertion.(?(A)A\d{2}\b|\b\d{3}\b)"A10", "910" in "A10 C103 910"
(?( name )yes | no )Matches yes if the named capture name has a match; otherwise, matches the optional no.(?< quoted>")?(?(quoted).+?"|\S+\s)Dogs.jpg, "Yiska playing.jpg" in "Dogs.jpg "Yiska playing.jpg""
8. Subtitutions

Adalah metode untuk me-replace dengan sebuah pola/pattern.

CharacterDescriptionPatternReplacement patternInput stringResulting string
$numberSubstitutes the substring matched by group number.\b(\w+)(\s)(\w+)\b$3$2$1"one two""two one"
${name}Substitutes the substring matched by the named groupname.\b(?< word1>\w+)(\s)(?< word2>\w+)\b${word2} ${word1}"one two""two one"
$$Substitutes a literal "$".\b(\d+)\s?USD$$$1"103 USD""$103"
$&Substitutes a copy of the whole match.(\$*(\d*(\.+\d+)?){1})**$& "$1.30""**$1.30**"
$`Substitutes all the text of the input string before the match.B+$`"AABBCC""AAAACC"
$'Substitutes all the text of the input string after the match.B+$'"AABBCC""AACCCC"
$+Substitutes the last group that was captured.B+(C+)$+"AABBCCDD"AACCDD
$_Substitutes the entire input string.B+$_"AABBCC""AAAABBCCCC"
9. Miscellaneous Constructs

Beberapa constructs tambahan yang bisa dimanfaatkan untuk ekstraksi string.

ConstructDefinitionExample
(?imnsx-imnsx)Sets or disables options such as case insensitivity in the middle of a pattern.\bA(?i)b\w+\b matches "ABA", "Able" in "ABA Able Act"
(?#comment)Inline comment. The comment ends at the first closing parenthesis.\bA(?#Matches words starting with A)\w+\b
[to end of line]X-mode comment. The comment starts at an unescaped # and continues to the end of the line.(?x)\bA\w+\b#Matches words starting with A
Regex Classes

Regex classes adalah classes yang digunakan dalam C# untuk melakukan operasi Regular Expressions. Berikut ini adalah daftar methods dari regex classes.

Sr.NoMethods
1public bool IsMatch(string input)
Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.
2public bool IsMatch(string input, int startat)
Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.
3public static bool IsMatch(string input, string pattern)
Indicates whether the specified regular expression finds a match in the specified input string.
4public MatchCollection Matches(string input)
Searches the specified input string for all occurrences of a regular expression.
5public string Replace(string input, string replacement)
In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.
6public string[] Split(string input)
Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.
Contoh program berikut ini mengilustrasikan pencocokan kata yang dimulai dengan huruf 'S'.

using System;
using System.Text.RegularExpressions;

namespace RegExApplication
{
   class Program
   {
      private static void showMatch(string text, string expr)
      {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc)
         {
            Console.WriteLine(m);
         }
      }
      
      static void Main(string[] args)
      {
         string str = "A Thousand Splendid Suns";
         
         Console.WriteLine("Matching words that start with 'S': ");
         showMatch(str, @"\bS\S*");
         Console.ReadKey();
      }
   }
}

Jika program dijalankan akan memberikan output sebagai berikut:

Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns

Berikut ini contoh program untuk mencocokkan kata yang diawali dengan 'm' dan diakhiri dengan 'e':

using System;
using System.Text.RegularExpressions;

namespace RegExApplication
{
   class Program
   {
      private static void showMatch(string text, string expr)
      {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc)
         {
            Console.WriteLine(m);
         }
      }
      static void Main(string[] args)
      {
         string str = "make maze and manage to measure it";

         Console.WriteLine("Matching words start with 'm' and ends with 'e':");
         showMatch(str, @"\bm\S*e\b");
         Console.ReadKey();
      }
   }
}

Setelah program dijalankan akan memberikan output sebagai berikut:

Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure

Contoh program berikut ini digunakan untuk mereplace white space:

using System;
using System.Text.RegularExpressions;

namespace RegExApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         string input = "Hello   World   ";
         string pattern = "\\s+";
         string replacement = " ";
         Regex rgx = new Regex(pattern);
         string result = rgx.Replace(input, replacement);

         Console.WriteLine("Original String: {0}", input);
         Console.WriteLine("Replacement String: {0}", result);    
         Console.ReadKey();
      }
   }
}

Seletelah program dijalankan akan memberikan output sebagai berikut:

Original String: Hello World   
Replacement String: Hello World 

Ok guys seperti itulah sekilas tentang regex, jika bingung itu biasa karena memang membingungkan untuk pertama kali menjamah regex. Tetapi dengan seiring waktu akan terbiasa menggunakan senjata ampuh yang satu ini. Sampai ketemu di tutorial selanjutnya Exception Handling.

Monday 24 October 2016

22. Preprocessor Directives C# (Basic/Dasar)

Preprocessor directive akan digunakan untuk melakukan pemrosesan pada code sebelum kompilasi program terjadi. Semua preprocessor directives dimulai dengan tag #, dan hanya boleh ada white spaces non character sebelum # tag. Perlu diketahui bahwa preprocessor directives bukanlah statement sehingga tidak perlu ada semicolon (;) pada akhir preprocessor.

Berbeda dengan preprocessor pada C++, preprocessor pada C# tidak digunakan untuk membuat macros, tetapi lebih ke instruksi dalam sebuah baris.

Preprocessor Directives Pada C#

Berikut ini adalah daftar preprocessor directive pada C#

Preprocessor DirectiveDescription.
#defineIt defines a sequence of characters, called symbol.
#undefIt allows you to undefine a symbol.
#ifIt allows testing a symbol or symbols to see if they evaluate to true.
#elseIt allows to create a compound conditional directive, along with #if.
#elifIt allows creating a compound conditional directive.
#endifSpecifies the end of a conditional directive.
#lineIt lets you modify the compiler's line number and (optionally) the file name output for errors and warnings.
#errorIt allows generating an error from a specific location in your code.
#warningIt allows generating a level one warning from a specific location in your code.
#regionIt lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor.
#endregionIt marks the end of a #region block.
Preprocessor #define

Preprocessor #define digunakan untuk membuat simbolik konstanta. Dengan menggunakan #define kita akan membuat sebuah konstanta yang nanti bisa kita gunakan untuk dievaluasi menggunakan preprocessor #if.

Misalnya kita ingin mendefinisikan konstan maka bisa dengan cara sebagai berikut:

#define symbol

Contoh program dibawah ini akan mengilustrasikan penggunaan preprocessor #defines:

#define PI 
using System;
namespace PreprocessorDAppl
{
   class Program
   {
      static void Main(string[] args)
      {
         #if (PI)
            Console.WriteLine("PI is defined");
         #else
            Console.WriteLine("PI is not defined");
         #endif
         Console.ReadKey();
      }
   }
}

Setelah program diatas dijalankan maka akan memberikan output sebagai berikut:

PI is defined

Conditional Directives

Kita bisa menggunakan #if directives untuk melakukan pengecekan pada sebuah simbol, sangat berguna untuk melakukan pengecekan apakah sebuah simbol bernilai benar atau salah.

Sintak untuk conditional directives adalahs sebagai berikut:

#if symbol [operator symbol]...

DImana symbol adalah symbol yang akan kita test, kita juga bisa menggunakan true atau false atau juga bisa menempelkan simbol negasi operator (!).

Operator yang bisa digunakan untuk conditional directives adalah sebagai berikut:

  • == (equality)
  • != (inequality)
  • && (and)
  • || (or)
Kita juga bisa mengelompokkan simbol dengan menggunakan tanda kurung buka tutup (). Conditional directives biasanya digunakan untuk membedakan configurasi, untuk mengecheck configurasi yang digunakan sebelum proses kompilasi program.

Contoh program dibawah ini akan mengilustrasikan penggunaan conditional directives:

#define DEBUG
#define VC_V10
using System;
public class TestClass
{
   public static void Main()
   {
      #if (DEBUG && !VC_V10)
         Console.WriteLine("DEBUG is defined");
      #elif (!DEBUG && VC_V10)
         Console.WriteLine("VC_V10 is defined");
      #elif (DEBUG && VC_V10)
         Console.WriteLine("DEBUG and VC_V10 are defined");
      #else
         Console.WriteLine("DEBUG and VC_V10 are not defined");
      #endif
      Console.ReadKey();
   }
}

Setelah program dijalankan akan memberikan output sebagai berikut:

DEBUG and VC_V10 are defined

Ok guys, sampai ketemu di tutorial selanjutnya Regular Expression.

Monday 17 October 2016

21. Namespaces C# (Basic/Dasar)

Namespace merupakan sebuah pengelompokan source code sehingga akan terpisah dari source code yang lain, atau jika temen temen akrab dengan Java namespace adalah package, sedangkan dalam bahasa pemrograman yang lain sering disebut sebagai modul.

Mendefinisikan Namespaces

Mendefinisikan namespace bisa dengan menggunakan kata kunci namespaces diikuti dengan nama namespaces.

namespace namespace_name
{
   // code declarations
}

Berikut adalah contoh untuk mengilustrasikan penggunaan namespaces

using System;
namespace first_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
}

namespace second_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside second_space");
      }
   }
}

class TestClass
{
   static void Main(string[] args)
   {
      first_space.namespace_cl fc = new first_space.namespace_cl();
      second_space.namespace_cl sc = new second_space.namespace_cl();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

Setelah program dijalankan akan memberikan output sebagai berikut

Inside first_space
Inside second_space

Using Keyword

Using keyword digunakan untuk mengimport namespaces ke dalam kode kita, penggunaan keyword using adalah dengan menggunakan using diikuti dengan nama namespace yang akan digunakan. Misalnya kita sudah mengimport namespaces System pada code kita maka untuk memanggil System.Console.WriteLine() cukup dengan:

Console.WriteLine ("Hello there");

Sedangkan jika kita tidak mendefinisikan using System pada kode kita maka kita perlu memanggil secara lengkap dengan:

System.Console.WriteLine("Hello there");

Berikut adalah contoh program untuk mengilustrasikan penggunaan kata kunci using untuk mengimport namespace pada kode kita.

using System;
using first_space;
using second_space;

namespace first_space
{
   class abc
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
}

namespace second_space
{
   class efg
   {
      public void func()
      {
         Console.WriteLine("Inside second_space");
      }
   }
}   

class TestClass
{
   static void Main(string[] args)
   {
      abc fc = new abc();
      efg sc = new efg();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

Setelah program dijalankan akan memberikan output sebagai berikut.

Inside first_space
Inside second_space

Nested Namespaces (Namespaces di dalam Namespaces)

Kita juga bisa mendifinisikan namespaces di dalam namespaces.

namespace namespace_name1
{
   // code declarations
   namespace namespace_name2
   {
      // code declarations
   }
}

Kita bisa menggunakan dot (.) untuk mengakses nested namespaces, contoh program berikut ini akan mengilustrasikan bagaimana memanggil namespaces dalam namespaces.

using System;
using first_space;
using first_space.second_space;

namespace first_space
{
   class abc
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
   namespace second_space
   {
      class efg
      {
         public void func()
         {
            Console.WriteLine("Inside second_space");
         }
      }
   }   
}
 
class TestClass
{
   static void Main(string[] args)
   {
      abc fc = new abc();
      efg sc = new efg();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

Setalah program dijalankan akan memberikan output sebagai berikut.

Inside first_space
Inside second_space

Ok guys, sampai ketemu di tutorial selanjutnya Preprocessor Directives.

Wednesday 12 October 2016

20. Interface C# (Basic/Dasar)

Hello guys pada bab sebelumnya kita pernah membahas tentang polymorphism, nah kali ini kita akan membahas bab interface yang mirip dengan polymorphism yaitu interface. Berbeda dengan abstract method dan virtual method, pada interface lebih mengarah ke template dari class. Sehingga dalam interface hanya terdapat nama method dan nilai kembalian tanpa ada implementasi method, sedangkan yang bertanggung jawab untuk mengimplementasikan method adalah class yang mengimplementasikan interface tesebut.

Pada inteface, selain method juga mendefinisikan properties dan event yang dimiliki oleh interface tesebut. Yang perlu diingat adalah dalam interface hanya terdapat declarasi tidak ada yang namanya inisialisasi.

Mendeklarasikan Interface

Berikut adalah format untuk interface, hanya terdapat deklarasi method, properti dan event.

public interface ITransactions
{
   // interface members
   void showTransaction();
   double getAmount();
}

Contoh berikut akan mengilustrasikan penggunaan interface:

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;

namespace InterfaceApplication
{
   public interface ITransactions
   {
      // interface members
      void showTransaction();
      double getAmount();
   }
   
   public class Transaction : ITransactions
   {
      private string tCode;
      private string date;
      private double amount;
      public Transaction()
      {
         tCode = " ";
         date = " ";
         amount = 0.0;
      }
      
      public Transaction(string c, string d, double a)
      {
         tCode = c;
         date = d;
         amount = a;
      }
      
      public double getAmount()
      {
         return amount;
      }
      
      public void showTransaction()
      {
         Console.WriteLine("Transaction: {0}", tCode);
         Console.WriteLine("Date: {0}", date);
         Console.WriteLine("Amount: {0}", getAmount());
      }
   }
   class Tester
   {
      static void Main(string[] args)
      {
         Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
         Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
         t1.showTransaction();
         t2.showTransaction();
         Console.ReadKey();
      }
   }
}

Setelah program dijalankan akan memberikan output sebagai berikut:

Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

Ok guys sampai ketemu di tutorial sejalnjutnya Namaspaces.