Pre
nego što i počnete da čitate ovaj post imajte u vidu da je on do sada jedan od
najvećih postova na ovom blogu i da nije dovoljno ga samo jednom pogledati iako
objašnjava samo suštinske promene koje nosi C# programerski jezik u verziji 7.0
. Takođe imajte u vidu da sam uložio izuzetno mnogo truda i vremena kako bi vam
na najjednostavniji mogući način objasnio šta vas čeka novo u C# 7.0 kodiranju.
Ali ove se promene ne mogu savladati odjednom već se sve uči korak po korak.
Svaki dan po malo. Ovom prilikom se takođe zahvaljujem svima na porukama,
podršci na društvenim mrežama i mom programerskom YouTube kanalu. Trenutno
najnovija verzija C# programskog jezika 7.0 sa sobom donosi mnogo promena koje
će vam definitivno omogućiti bolje i brže kodiranje. Microsoft Visual Studio2017 sa sobom nosi izuzetno moćne alate sa kojima će vaši programi u C# programskom jeziku i projekti definitivno biti sve više funkcionalni u sve
većim i kompleksnijim poslovnim zahtevima.
( Microsoft konferencija, šta je novo u C# 7.0 )
Poznavanje
programskog jezika C# u verziji 7.0 definitivno ima svoje prednosti. C# programski jezik i pored toga što se ne kotira visoko na listi programskih
jezika; polako ali sigurno preuzima vodstvo na najkomplikovanijim poslovnim rešenjima. C# programski jezik koristi preko 2 miliona programera u celom svetu, sve se
više koristi na univerzitetima i definitivno nije mrtav programski jezik. I ja
sam čak razmišljao da pređem na PHP programski jezik, ali kad pogledam koliko
truda i šta se sve poboljšalo u zadnje vreme u C# programskom jeziku, što bi
rekli kod nas koliko je taj jezik uzeo maha; jednostavno ostajem i dalje privržen
Microsoft tehnologijama koji mi omogućavaju da programiram na bilo kojoj platformi.
Većini početnika se danas može izgubiti u C# programskom jeziku i umesto da na
ovaj programski jezik gledaju kao na najbolji i najlakši programskog jezik, oni
kolutaju očima kad vide par linija code-a u programu. To je zbog nestrpljenja i
želje da se odmah sve zna. Pogledajte sadržaj na mom blogu i krenite da
programirate jedan po jedan program. Ne možete sve odjednom, ni ovaj post a tek blog nije napravljen odjednom. Budite
disciplinovani i programirajte svaki dan makar pola sata, ali svaki dan. To je najbolji
metod za učenje jer se C# programski jezik zbog sve većeg progresa i primene u
svemu je robustan i lako se zaboravlja kad se ne koristi. Otkucajte code isti
kao u mojim primerima, zatim izmislite neki mali svoj vlastiti sličan primer i
njega programirajte jer se najbolje pamti kad kodirate nešto iz vaše glave.
Pogledajte sada šta je sve novo u C# programskom jeziku u verziji 7.0.
Literal
digitalni separator i binarni literali
Iako
su ove dve male promene na literalima planirane u C# programskom jeziku u verziji 6.0, one su realizovane tek u C# programskom jeziku u verziji 7.0. Zbog sve više code-a i kompleksnosti programiranja u velikim projektima
stalno se balansira između čitljivosti code-a i optimizacije. Digitalni separator
je mala ali značajna promena u kodiranju jer kad u code-u pišete velike
brojeve, ti brojevi su slabo čitljivi.
// digit
literals in c# 6.0 sometimes looks unreadably
int itemCost = 2000000;
double salesTax
= 0.075;
Da
bi ste bili sigurni da je navedena cifra 2 miliona i nije 200 hiljada često
trebate da prebrojite nule. Zamislite da sad u programu imate mnoštvo ovakvih
podataka. Dobro, ja bi u tom slučaju zaključio da je celi program pogrešno
programiran, kad imate mnoštvo brojeva dodeljenih promenjivima bolje da ih
držite u bazi podataka, nego u code-u. Ali vratimo se nečitljivosti. Tada bi
nam to oduzimalo i dosta vremena. Sad zahvaljujući upotrebom digitalnog separatora,
čitljivost velikih brojeva je čitljivija i mi možemo na prvi pogled biti
sigurni da je navedena cifra 2 miliona.
// in c#
7.0 you can use the digit seperator with numbers
itemCost
= 2_000_000;
salesTax = 0.0_75;
Digitalne
separatore možete da stavite na bilo kojoj decimali, niste ograničeni. Ali isto
tako niste ograničeni na decimalne brojeve. Heksadecimalni brojevi takođe mogu
koristiti digitalne separatore.
// in c#
7.0 you can use the digital seperator with hexadecimal numbers
itemCost = 0xF_42_40; // 1 000 000 in hexadecimal
Digitalne
separatore možete čak da koristite i za binarne brojeve. Međutim da bi vam digitalni separator radio sa
binarnim brojevima, neophodno je da koristite 0b prefiks.
// in c#
7.0 you can use bit literals too if you use 0b prefix
itemCost = 0b1111_01_0000_1001_0000_0000;
// 4 000 000 in binary numbers
Pogledajte
sada code celog programa:
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Literals
{
class Program
{
static void Main(string[] args)
{
// digit
literals in c# 6.0 sometimes looks unreadably
int itemCost = 2000000;
double salesTax = 0.075;
Print(itemCost, salesTax);
// in c# 7.0
you can use the digit seperator with numbers
itemCost = 2_000_000;
salesTax = 0.0_75;
Print(itemCost, salesTax);
// in c# 6.0
you can add a hexadecimal value to work like as decimal
itemCost = 0xF4240; // 1 000 000 in hexadecimal
Print(itemCost, salesTax);
// in c# 7.0
you can use the digital seperator with hexadecimal numbers
itemCost = 0xF_42_40; // 1 000 000 in hexadecimal
Print(itemCost, salesTax);
// in c# 7.0
you can use bit literals too if you use 0b prefix
itemCost =
0b1111_01_0000_1001_0000_0000; // 4 000 000 in binary
numbers
Print(itemCost, salesTax);
WriteLine(Environment.NewLine + "Press any kay to continue...");
ReadKey();
}
static void Print (int item, double tax)
{
Write($"Item costs {item} and total sales tax is {item * tax} dollars."
+ Environment.NewLine + $"So, the finall price is {item +
item * tax} dollars.");
ReadLine();
WriteLine();
}
}
}
Kada
pokrenete navedeni program, on će vam prikazati sledeće rezultate:
Item
costs 2000000 and total sales tax is 150000 dollars.
So,
the finall price is 2150000 dollars.
Item
costs 2000000 and total sales tax is 150000 dollars.
So,
the finall price is 2150000 dollars.
Item
costs 1000000 and total sales tax is 75000 dollars.
So,
the finall price is 1075000 dollars.
Item
costs 1000000 and total sales tax is 75000 dollars.
So,
the finall price is 1075000 dollars.
Item
costs 4000000 and total sales tax is 300000 dollars.
So,
the finall price is 4300000 dollars.
Press
any kay to continue...
Kako
to sve izgleda možete pogledati i na video-u:
( What's new in C# 7.0 - #1. Literals )
Lokalne
funkcije
Lokalne
funkcije su vam funkcije unutar neke metode. U C# programskom jeziku u verziji 7.0, vi
možete da pišete funkciju u metodi. To ima smisla ukoliko će samo metoda
koristiti tu funkciju. Zato se zovu lokalne jer su uvek privatne. Ne mogu biti
statične, za tako nešto nema ni potrebe, ali se metoda u kojoj se nalazi
lokalna funkcija može biti statična. Lokalna funkcija se može pozivati više
puta sa bilo kog mesta u metodi.
// local
function cannot be static but it can be in a static method
public static void Print(string fullName)
{
if (fullName == String.Empty) return;
DisplayText();
// local
function
void DisplayText()
{
string space = ".....";
WriteLine();
foreach (char s in fullName)
{
space += "...";
WriteLine(space + " " + fullName);
}
}
}
Kao
što vidite lokalna funkcija DisplayText se nalazi u metodi Print i cela svrha
metode je da pozove lokalnu funkciju ukoliko string nije prazan. Za ovaku svrhu
nije baš najbolje da koristite lokalnu funkciju u svom programu nego sam to
uradio radi što jednostavnijeg primera, da bi vam bilo jasno kako se koristi. Pogledajte
celi program.
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LocalFunctions
{
class Program
{
static void Main(string[] args)
{
// local
functions are functions inside the exicting method
// it can call
from everywhere inside the method
Write("What's your first name? ");
string fName = ReadLine();
Write("What's your last name? ");
string lName = ReadLine();
string fullName = fName + " " + lName;
Print(fullName);
WriteLine(Environment.NewLine + "Press any key to continue...");
ReadKey();
}
// local function
cannot be static but it can be in a static method
public static void Print(string fullName)
{
if (fullName == String.Empty) return;
DisplayText();
// local
function
void DisplayText()
{
string space = ".....";
WriteLine();
foreach (char s in fullName)
{
space += "...";
WriteLine(space + " " + fullName);
}
}
}
}
}
Kada
pokrenete navedeni program, on će vam prikazati slične sledeće rezultate u
zavisnosti kakvo ste ime uneli kao unos podataka.
What's
your first name? Manuel
What's
your last name? Radovanovic
........
Manuel Radovanovic
...........
Manuel Radovanovic
..............
Manuel Radovanovic
.................
Manuel Radovanovic
....................
Manuel Radovanovic
.......................
Manuel Radovanovic
..........................
Manuel Radovanovic
.............................
Manuel Radovanovic
................................
Manuel Radovanovic
...................................
Manuel Radovanovic
......................................
Manuel Radovanovic
.........................................
Manuel Radovanovic
............................................
Manuel Radovanovic
...............................................
Manuel Radovanovic
..................................................
Manuel Radovanovic
.....................................................
Manuel Radovanovic
........................................................
Manuel Radovanovic
...........................................................
Manuel Radovanovic
Press
any key to continue...
Kako
to sve izgleda možete pogledati i na video-u:
( What's new in C# 7.0 - #2. Local Functions )
Expression
Bodied članovi
Naslov
nije greškom napisan polovično na engleskom jeziku. Jednostavno ne znam kako bi
se celi izraz preveo na srpski jezik iako je cela upotreba iste u programiranju
prosto jednostavna. Suština je da programerske celine poput metode pišete
kraće. Ova mogućnost se pojavljuje još u C# programskom jeziku u 6.0 verziji gde jeste
dodata podrška za Expression Bodied članove ali u verziji C# 7.0 programskog
jezika, Microsoft je još proširio i dozvolio članovima da se ponašaju kao Expression.
Tako Expression Bodied članove možete sad koristiti i u konstruktoru, propertijima
i čak u destruktorima. Najbolje da pogledate code i sve će vam biti jasnije,
nego da vas zbunjujem engleskim izrazima koje programeri izgovaraju na engleskom jeziku i kad pričaju srpski. Sledeći program sadrži dve klase Book1 i Book2.
Klasa Book1 koristi klasične C# 6.0 članove dok klasa Book2 je identična, samo
koristi Expression Bodied članove. Sami uočite razliku.
class Book1
{
// classic full
property
private string _book;
public string Book
{
get { return _book; }
set
{
//
classic condition with throw statment
if (value == null) throw new ArgumentNullException(
"Value cannot be null!");
_book = value;
}
}
// classic
constructor
public Book1(string book)
{
Book = book;
}
// classic
destructor
~Book1()
{
Debug.WriteLine(Environment.NewLine + "Destructor from Book1 was
called.");
}
}
Pogledajte
sad klasu Book2 i uporedite je sa prethodnom. Uočavate li razliku u kodiranju?
class Book2
{
// new C# 7.0
property
private string _book;
public string Book
{
get => _book;
set => _book = value ?? throw new ArgumentNullException(
"Value cannot be null!");
}
// new C# 7.0
constructor
public Book2(string book)
=> Book = book;
// new c# 7.0
destructor
~Book2() => Debug.WriteLine(Environment.NewLine +
"Destructor from Book2 was called.");
}
Ista
stvar ali napisana kraće zahvaljujući Expression Bodied članovima. Pogledajte code
celog programa kako izgleda.
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ExpressionBodiedMembers
{
class Program
{
static void Main(string[] args)
{
Book1 book1 = new Book1("C# 6
and .Net Core 1.0");
Book2 book2 = new Book2("C# 7
and .Net Core CookBook");
WriteLine("Uses Book1 class with the classic full property, " +
"constructor and destructor");
WriteLine(Environment.NewLine + book1.Book + Environment.NewLine);
WriteLine("Uses Book2 class with new C# 7 full property,"
+ "constructor and destructor");
WriteLine(Environment.NewLine + book2.Book + Environment.NewLine);
WriteLine(Environment.NewLine + "Press any key to continue...");
ReadKey();
}
}
class Book1
{
// classic full
property
private string _book;
public string Book
{
get { return _book; }
set
{
//
classic condition with throw statment
if (value == null) throw new ArgumentNullException(
"Value cannot be null!");
_book = value;
}
}
// classic
constructor
public Book1(string book)
{
Book = book;
}
// classic
destructor
~Book1()
{
Debug.WriteLine(Environment.NewLine + "Destructor from Book1 was
called.");
}
}
class Book2
{
// new C# 7.0
property
private string _book;
public string Book
{
get => _book;
set => _book = value ?? throw new ArgumentNullException(
"Value cannot be null!");
}
// new C# 7.0
constructor
public Book2(string book)
=> Book = book;
// new c# 7.0
destructor
~Book2() => Debug.WriteLine(Environment.NewLine +
"Destructor from Book2 was called.");
}
}
Kada
pokrenete navedeni program, on će vam prikazati sledeće rezultate. Obe klase će
odraditi isti posao.
Uses
Book1 class with the classic full property, constructor and destructor
C#
6 and .Net Core 1.0
Uses
Book2 class with new C# 7 full property,constructor and destructor
C#
7 and .Net Core CookBook
Press
any key to continue...
Kako
to sve izgleda možete pogledati i na video-u:
( What's new in C# 7.0 - #3. Expression Bodied Members )
Throw
Exception
U C# programskom jeziku u verziji 6.0, Throw Exception je samo iskaz i kao takav je
bio ograničen da se ne može koristiti na određenim mestima. Zahvaljujući Expressions
Bodied članovima sada se Throw Exception koristi kao da je Expression. Npr. u
funkciji:
public static int CheckLength(string word) => word.Length > 0 ?
word.Length : throw new Exception(
"Throwing inside conditional operator expressions: "
+ Environment.NewLine + "Word cannot be empty!");
Ili
u konstruktoru:
public Student (string
firstName) => firstName = FirstName ?? throw new Exception (
"Throwing inside expression bodied constructor:" +
Environment.NewLine + "First name cannot be empty!");
Ili
direktno u Try Catch strukturi:
try
{
string NotAllowed = word ?? throw new Exception("Throwing
inside null-coalescing operator
expressions:" + Environment.NewLine + "Word cannot be null!");
}
catch (Exception ex)
{
WriteLine(ex.Message);
}
Pogledajte
kako izgleda celi program:
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ThrowExpressions
{
class Program
{
static void Main(string[] args)
{
// in c# 6.0
throwing exceptions had certain limitations where they could be used
// because
throw was a statment. in c# 7.0 thanks to expression-bodied members,
// throw is an
expressions
string word = null;
//
null-coalescing
try
{
string NotAllowed = word ?? throw new Exception("Throwing
inside null-coalescing operator expressions:" +
Environment.NewLine + "Word cannot be null!");
}
catch (Exception ex)
{
WriteLine(ex.Message);
}
ReadLine();
// conditional
operator
try
{
word = String.Empty;
CheckLength(word);
}
catch (Exception ex)
{
WriteLine(ex.Message);
}
ReadLine();
// constructor
try
{
Student student = new Student(String.Empty);
}
catch (Exception ex)
{
WriteLine(ex.Message);
}
ReadLine();
WriteLine(Environment.NewLine + "Press any key to continue...");
ReadKey();
}
public static int CheckLength(string word) => word.Length > 0 ?
word.Length : throw new Exception(
"Throwing inside conditional operator expressions: "
+ Environment.NewLine + "Word cannot be empty!");
}
class Student
{
public string
FirstName { get; set; }
public Student (string
firstName) => firstName = FirstName ?? throw new Exception (
"Throwing inside expression bodied constructor:" +
Environment.NewLine + "First name cannot be empty!");
}
}
Kada
pokrenete navedeni program, on će vam prikazati sledeće rezultate:
Throwing
inside null-coalescing operator expressions:
Word
cannot be null!
Throwing
inside conditional operator expressions:
Word
cannot be empty!
Throwing
inside expression bodied constructor:
First
name cannot be empty!
Press
any key to continue...
Kako
to sve izgleda možete pogledati i na video-u:
( What's new in C# 7.0 - #4. Throwing Exceptions in Expressions )
Out
promenjive
U C# programskom jeziku u ranijim verzijama vi ste pre upotrebe out promenjive prvo
morali da deklarišete promenjivu iznad out iskaza. U C# programskom jeziku u
verziji 7.0 vi možete da deklarišete istu promenjivu od tačke gde out iskaz
počinje. Možete pomisliti da to nije neka značajna promena ali recimo smanjuje vaš
program za jednu liniju koda. Takođe sa out iskazom sada može koristiti i tip podataka
var. Pogledajte celi mali program koji ilustruje upotrebu out promenjive.
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OutVariables
{
class Program
{
static void Main(string[] args)
{
// in C# 6.0
you have to first declare a variable to use an out parameter
int number1;
Write("Enter a number between 1 and 10 : ");
bool n1 = int.TryParse(ReadLine(),
out number1);
WriteLine($"You entered number {number1}." + Environment.NewLine);
// in C# 7.0
you can declare the out variable at the point where it is passed as an out
parameter
Write("Enter a number between 10 and 100 : ");
bool n2 = int.TryParse(ReadLine(),
out int number2);
WriteLine($"You entered number {number2}." + Environment.NewLine);
// in c# 7.0
you can declare the out variable with var keyword
Write("Enter a number between 100 and 1000 : ");
bool n3 = int.TryParse(ReadLine(),
out var number3);
WriteLine($"You entered number {number3}." + Environment.NewLine);
WriteLine($"Sum of your numbers are {number1} + {number2} + {number3} " +
$"= {number1 + number2 + number3}");
WriteLine(Environment.NewLine + "Press any key to continue...");
ReadKey();
}
}
}
Kada
pokrenete navedeni program, on će vam prikazati slične sledeće rezultate u
zavisnosti koje brojeve ste uneli kao unos u out promenjive.
Enter
a number between 1 and 10 : 8
You
entered number 8.
Enter
a number between 10 and 100 : 88
You
entered number 88.
Enter
a number between 100 and 1000 : 888
You
entered number 888.
Sum
of your numbers are 8 + 88 + 888 = 984
Press
any key to continue...
Kako
to sve izgleda možete pogledati i na video-u:
( What's new in C# 7.0 - #5. Out Variables )
Reference
kroz Return i lokalne promenjive
U
ranijim verzijama C# programskog jezika referenciranje i upotreba Ref nije
ništa novo. Ali sad od C# verzije 7.0 programskog jezika vi možete vraćati
referentne objekte kroz Return i smeštati ih u lokalne promenjive. Moja pretpostavka
zašto je Microsoft ovaj put dao važnost referentnim tipovima podataka leži u
činjenici da postoje iskusni C++ programeri koji još uvek nisu prešli na C# upravo zbog referenci i pokazivača. Kako god da vi kodirate neki projekat, na
kraju on prolazi kroz optimizaciju. Zato upotreba referentnih tipova je
poželjnija posebno ako programirate igrice. Obratite pažnju na funkcije koje
koriste referentne tipove podataka i kako se one sada referenciraju.
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace References
{
class Program
{
static void Main(string[] args)
{
// copy value
types
int a = 18;
int b = a;
WriteLine("C# 6.0 - Copy value types");
WriteLine($" a = {a}" + Environment.NewLine +
$" b = a // {b}" + Environment.NewLine);
a = 48;
WriteLine("Value types will not change value b when change a : ");
WriteLine($" a = 48 ... a = {a} and b = {b}" + Environment.NewLine);
// ref value
types
ref int c = ref a;
WriteLine("C# 7.0 - Copy ref types");
WriteLine($" a = {a}" + Environment.NewLine +
$" c = a // {c}" + Environment.NewLine);
WriteLine("Value types will change value c when change a : ");
a = 72;
WriteLine($" a = 72 ... a = {a} and c = {c}" + Environment.NewLine);
// reference
return
int d = 99;
WriteLine("C# 7.0 - Reference return ");
WriteLine($" a = {a} and d = {d} and the bigger number is " +
$"{Max(ref a, ref d)}");
d = 20;
WriteLine($" After change d
= 20 you will got this... the bigger number is " +
$"{Max(ref a, ref d)}");
WriteLine();
// array
reference
int[] someArray = { 1, 2, 3, 4, 5 };
WriteLine("C#
7.0 - You can use reference type for change array elements.");
Write(" Read array:
");
ReadArray(someArray);
Write(Environment.NewLine + " Change last
element: ");
// change last
element with reference type
ref int e = ref ChangeLastElement(someArray);
e = 100;
ReadArray(someArray);
WriteLine();
WriteLine(Environment.NewLine + "Press any key to continue...");
ReadKey();
}
static public ref int Max(ref int first, ref int second)
{
if (first > second) return ref first;
return ref second;
}
static void
ReadArray(Array array)
{
foreach (int item in array)
{
Write(item + ", ");
}
}
static public ref int ChangeLastElement(int[]array)
{
return ref
array[array.Length - 1];
}
}
}
Kada
pokrenete navedeni program, on će vam prikazati sledeće rezultate:
C#
6.0 - Copy value types
a = 18
b = a // 18
Value
types will not change value b when change a :
a = 48 ... a = 48 and b = 18
C#
7.0 - Copy ref types
a = 48
c = a // 48
Value
types will change value c when change a :
a = 72 ... a = 72 and c = 72
C#
7.0 - Reference return
a = 72 and d = 99 and the bigger number is
99
After change d = 20 you will got this...
the bigger number is 72
C#
7.0 - You can use reference type for change array elements.
Read array: 1, 2, 3, 4, 5,
Change last element: 1, 2, 3, 4, 100,
Press
any key to continue...
Kako
to sve izgleda možete pogledati i na video-u:
( What's new in C# 7.0 - #6. Referencing Variables, Return and Arrays )
Pattern
Matching
U C# programskom jeziku u verziji 7.0; Pattern Matching je novitet koji vam služi da lakše upoređujete
i testirate tipove podataka. To je apsolutno novi koncept Patterns – obrazca koji
proverava tipove podataka da li imaju specifičan tip podataka. Pogledajte ovaj code
programa, ali posebno obratite pažnju na code koji u statičnoj metodi Print
proverava da li tip podataka pripada Student klasi ili Professor. Na koji način
on to radi?
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PatternMatching
{
class Program
{
static void Main(string[] args)
{
// new
structure Pattern Matching in C# 7.0 test values in different ways
Professor professor = new Professor("Sophia", "Anderson", "English",
new DateTime(1990, 10, 5), "Solt Lake
City", "Utah");
Print(professor);
Student student = new Student("Manuel", "Radovanovic", "English",
new DateTime(1975, 10, 5), "Belgrade", "Serbia");
Print(student);
WriteLine(Environment.NewLine + "Press any key to continue...");
ReadKey();
}
static void Print(object person)
{
// pattern
matching structure for a student
if (person is Student student)
{
WriteLine($"Subject: {student.Subject}");
WriteLine($"Student: {student.FullName}");
WriteLine($"Age: {Ages(student.Birthday)}");
WriteLine($"City: {student.City}");
WriteLine($"State: {student.State}");
WriteLine(new String('-', 20) + Environment.NewLine);
}
// pattern
matching structure for professor
if (person is Professor professor)
{
WriteLine($"Subject: {professor.Subject}");
WriteLine($"Professor: {professor.FullName}");
WriteLine($"Age: {Ages(professor.Birthday)}");
WriteLine($"City: {professor.City}");
WriteLine($"State: {professor.State}");
WriteLine(new String('-', 20) + Environment.NewLine);
}
// local
function
string Ages(DateTime date)
{
date = DateTime.Today.AddYears(-date.Year);
return date.Year.ToString();
}
}
}
class Person
{
public string
FirstName { get; set; }
public string LastName
{ get; set; }
public string FullName
{ get; set; }
public DateTime Birthday { get; set; }
public string City { get; set; }
public string State { get; set; }
}
class Student : Person
{
public string Subject { get; set; }
public Student(string
firstName, string lastName, string subject,
DateTime birthDate, string city, string state)
{
FirstName = firstName;
LastName = lastName;
FullName = firstName + " " + lastName;
Subject = subject;
Birthday = birthDate;
City = city;
State = state;
}
}
class Professor : Person
{
public string Subject
{ get; set; }
public Professor(string
firstName, string lastName, string subject,
DateTime birthDate, string city, string state)
{
FirstName = firstName;
LastName = lastName;
FullName = firstName + " " + lastName;
Subject = subject;
Birthday = birthDate;
City = city;
State = state;
}
}
}
Kada
pokrenete navedeni program, on će vam prikazati sledeće rezultate:
Subject:
English
Professor:
Sophia Anderson
Age:
27
City:
Solt Lake City
State:
Utah
--------------------
Subject:
English
Student:
Manuel Radovanovic
Age:
42
City:
Belgrade
State:
Serbia
--------------------
Press
any key to continue...
Kako
to sve izgleda možete pogledati i na video-u:
( What's new in C# 7.0 - #7 Pattern Matching )
Pattern
Matching – Switch Case struktura
Iako
bi promene na Switch Case strukturi mogao pripojiti Pattern Matching novitetu,
smatram da je Switch Case struktura kroz Pattern Matching jedna od najbitnijih
promena u C# programskom jeziku u verziji 7.0 jer će te je u budućim projektima itekako koristiti.
Samo iz tog razloga pogledajte poseban Pattern Matching program samo za strukturu Switch Case koja sad može evulirati. Takođe možete u Case klazuli dodavati nove
uslove. Obratite pažnju na Switch Case strukturu.
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SwitchCaseStatment
{
class Program
{
static void Main(string[] args)
{
object parent = "Emily Tatman";
object guest = null;
object student1 = new Student("Ethan", "Hamblent", 20);
object student2 = new Student("Anna", "Craston", 16);
object professor = new Professor("Kevin", "Lee", 45);
object principal = new Principal("Lauren", "Austin", 55);
Visitor(parent);
Visitor(guest);
Visitor(student1);
Visitor(student2);
Visitor(professor);
Visitor(principal);
WriteLine(Environment.NewLine + "Press any key to continue...");
ReadKey();
// local
function
void Visitor(object person)
{
// switch
case statment with new C# 7.0 pattern maching structure
switch (person)
{
case string str:
WriteLine($"Object which is string: {parent}");
break;
case Student stu when
stu.FirstName is "Anna":
WriteLine($"Student which first name is Anna: {stu.FullName}");
break;
case Student stu when stu.Age
> 16:
WriteLine($"Student which has more ages than 15: {stu.FullName} {stu.Age} yeras.");
break;
case Professor prof:
WriteLine($"Professor: {prof.FullName}");
break;
case Principal prin:
WriteLine($"Principal: {prin.FullName}");
break;
default:
WriteLine("Guest: No guests, the object is null.");
break;
}
}
}
}
class Person
{
public string
FirstName { get; set; }
public string LastName
{ get; set; }
public byte Age { get; set; }
}
class Student : Person
{
public string FullName
{ get; set; }
public Student (string
firstName, string lastName, byte age)
{
FirstName = firstName;
LastName = lastName;
FullName = FirstName + " " + LastName;
Age = age;
}
}
class Professor : Person
{
public string FullName
{ get; set; }
public Professor(string
firstName, string lastName, byte age)
{
FirstName = firstName;
LastName = lastName;
FullName = FirstName + " " + LastName;
Age = age;
}
}
class Principal : Person
{
public string FullName
{ get; set; }
public Principal (string
firstName, string lastName, byte age)
{
FirstName = firstName;
LastName = lastName;
FullName = FirstName + " " + LastName;
Age = age;
}
}
}
Kada
pokrenete navedeni program, on će vam prikazati sledeće rezultate:
Object
which is string: Emily Tatman
Guest:
No guests, the object is null.
Student
which has more ages than 15: Ethan Hamblent 20 yeras.
Student
which first name is Anna: Anna Craston
Professor:
Kevin Lee
Principal:
Lauren Austin
Press
any key to continue...
Kako
to sve izgleda možete pogledati i na video-u:
( What's new in C# 7.0 - #8. Pattern Matching - Switch Case Statement )
Tuples
Tuple
… ili što bi se čitalo kao tjupl na srpskom jeziku je nova struktura u C# programskom
jeziku u verziji 7.0. Većina programera je smatra najbitnijim novitetom. To je
sasvim nova struktura zasnovana na više delova dok predstavlja celinu. Međutim da
bi ste koristili Tuples strukture morate uvesti ovu mogućnost u vaš projekat
preko NutGet Package for solution. Kako se to radi, najbolje pogledajte u
video-u. Ali pre toga obratite pažnju na code celog programa kako bi vam bilo
jasnije kako se koriste Tuples.
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tuples
{
class Program
{
static void Main(string[] args)
{
// YOU MUST ADD
VALUE TUPLE REFERENCE IN YOUR PROJECT
// FROM MANAGE
NUTGET PACKAGE FOR SOLUTION ... TO USE TUPLES
// You can
write value types like as this
ValueTuple<string, string, string> Languages = ("English", "German", "Spanish" );
// You can
write value types shorter
(string, string, int) Student = ("Manuel", "Radovanovic", 2017);
WriteLine($"Student, {Student.Item3} generation - {Student.Item1} {Student.Item2}");
// You can name
elements in tuple declaration
(string firstName, string
lastName, int generation) = ("Eileen", "Collins", 2017);
WriteLine($"Student, {generation} generation - {firstName} {lastName}" + Environment.NewLine);
WriteLine($"{ Student.Item1} learns {Languages.Item1}, {Languages.Item2} and {Languages.Item3} languages.");
// Let's change
values
Languages = ("Bosnian", "Croatian", "Serbian");
WriteLine($"{firstName} learns {Languages.Item1}, {Languages.Item2} and {Languages.Item3} languages.");
//
Deconstruction of Non-Tuple Types
var place = new Cities { City = "Salt Lake City", State = "Utah" };
var (pc, ps) = place;
WriteLine(Environment.NewLine + $"Conference in {pc}, {ps}.");
WriteLine(Environment.NewLine + "Press any key to continue...");
ReadKey();
}
}
class Cities
{
public string City { get; set; }
public string State { get; set; }
public void
Deconstruct(out string city, out string state)
{
city = City;
state = State;
}
}
}
Kada
pokrenete navedeni program, on će vam prikazati sledeće rezultate:
Student,
2017 generation - Manuel Radovanovic
Student,
2017 generation - Eileen Collins
Manuel
learns English, German and Spanish languages.
Eileen
learns Bosnian, Croatian and Serbian languages.
Conference
in Salt Lake City, Utah.
Press
any key to continue...
Kako
to sve izgleda možete pogledati i na video-u:
( What's new in C# 7.0 - #9. Tuples )
No comments:
Post a Comment