Understanding C# DateTime Class
Understanding C# DateTime Class
1. 2. DEFINITION--------------------------------------------------(2) ►DT is a struct in System nmespc tht alows storin date & tym values, ►it is imutble, opration retn new instanc.
3. SYNTAX
1) Default DateTime Format-------------------------------(1) ► default format of DateTime : “yyyy-MM-dd hh:mm:[Link] tt”, ►yyyy: year, MM: month, dd:day, hh:hour, mm:minutes, ss: seconds, fff:milliseconds, tt:am/pm
2) Creating A DateTime Instance For A Date & Time (3) ►DateTime dtName = new DateTime();, ►(yyyy, MM, dd) date only, ►(yyyy, MM, dd, hh, mm, ss, fff, DateTimeKind) date & time, ► DateTimeKind:Local, Utc, Unspecified
3) Creating A DateTime Property in A Class----------- (1) ►pub cls Person{ pub string Name{get; set;} pub DateTime dob {get; set;} }, || ►var person = new Person(); [Link] = “faraz”; [Link] = [Link](“1991-10-11 [Link].999 am”); CW([Link]);
1.1- DATETIME INSTANCE PROPERTIES
1- [Link] 2- [Link] 3- [Link] 4- [Link] 5- [Link]
• get DT typ date only (time set to [Link]) • get int typ day of month (1-31). • get DayOfWeek as enum (day name). DayOfWeek typ • get int typ day of year (1-366) • get int typ month componnt (1-12)
• DateTime dt = new DateTime(2023, 10, 5, 14, 30, 0); • DateTime dt = new DateTime(2023, 10, 5); • DateTime dt = new DateTime(2023, 10, 5); • DateTime dt = new DateTime(2023, 12, 31); • DateTime dt = new DateTime(2023, 12, 31);
DateTime dateOnly = [Link]; int day = [Link]; DayOfWeek dayOfWeek = [Link]; int dayOfYear = [Link]; int month = [Link];
[Link](dateOnly); //10/5/2023 [Link] AM [Link](day); // Output: 5 [Link](dayOfWeek); // Output: Thursday [Link](dayOfYear); // Output: 365 [Link](month); // Output: 12
6- [Link] 7- [Link] 8- [Link] 9- [Link] 10- [Link]
• get int typ year (2025 etc) • get int typ hour (0-24) • get int typ minutes (0-60) • get int typ seconds(0-60) • get int typ millisecond
• DateTime dt = new DateTime(2023, 10, 5); • DateTime dt = new DateTime(2025,05,03,5,1,0); • DateTime dt = new DateTime(2023, 10, 5, 14, 30, 0); • var dt = new DateTime(2023, 10, 5, 14, 30, 36,962); • var dt = new DateTime(2023, 10, 5, 14, 30, 36,962);
int year = [Link]; int hour = [Link]; int minute = [Link]; int second = [Link]; int millisecond = [Link];
[Link](year); // Output: 2023 [Link](hour); // Output: 5 [Link](minute); // Output: 30 [Link](second); // Output: 36 [Link](millisecond); // Output: 962
1.2 DATETIME STATIC PROPERTIES
1- [Link] 2- [Link] 3- [Link] 4- [Link] 11- [Link]
• gets DT typ current local date & time • gets DT typ current utc date & tym. • get DTK typ kind: local, utc, coordinated or neither. • get DT typ todays date onlyv(time set to [Link]) • it gets time hh:mm:[Link] 4m gvn date time instance.
• DateTime now = [Link] • var now = [Link]; • var dt = new DateTime(2023, 10, 5, 14, 30, 36, 962); • DateTime dt = [Link]; • DateTime dt = [Link];
[Link]([Link]()); [Link]([Link]()); [Link]([Link]); //Unspecified [Link]([Link]()); [Link]([Link]());
// 03-05-2025 [Link] // 03-05-2025 [Link] • [Link]([Link]); //Local // 03-05-2025 [Link] //[Link].3789566
1.3 DATATIME STATIC METHODS
1- [Link](DateTime1, DateTime2) 2- [Link](year, month) 3- [Link](year) 4- [Link](valid datetime string) 5- [Link](DateTimeString)
• Compares two dates. Returns int -1, 0, or 1 • Returns int typ number of days in a month. • Checks if a year is a leap year return bool. • Converts a string to DateTime. Retrn DateTime • convrt gvn string 2 a datetime instnc.
• t1 < t2→ -1 • t1 == t2→0 • t1 > t2→ 1 • int days = [Link](2024, 2); • bool isLeap = [Link](2024); • string dateStr = "May 3, 2025"; • DateTime date = [Link]("2025-05-03");
• DateTime t1 = new DateTime(2025, 5, 3); [Link](days); [Link](isLeap); //true DateTime date = [Link](dateStr); [Link](date); //5/3/2025 [Link] AM
DateTime t2 = new DateTime(2025, 5, 4); // it retrns 29 as 2024 was a leap year [Link](date);
int result = [Link](t1, t2); 5- [Link](DateTimeString, formatString, FormatProvider)
[Link](result); //-1
• Parses a string using a specific format gvn by user. • datetime string and format string must match or err. • add using: [Link]
• provider: [Link] • providr 2: [Link] (opt)
• var date = [Link]("03-05-2025","dd- MM-yyyy", [Link]); [Link](date); // 5-3-2025 [Link] AM
1.4 DATETIME INSTANCE METHODS
TIMESPAN struct 1- [Link](years) +/- 2- [Link](months); +/- 3- [Link]([Link]); +/- 4- [Link]([Link]); +/-
• timspn is durtion of tym, study ltr, folwin r constrctrs • Add yrs 2 date ret DT. Adjusts February 29 in leap yr. • add months 2 date ret DT, adjst 4 end of month cases. • Adds days in +, -, fraction. Retn DateTime. • Adds hours to the DateTime retrn DT.
• TimeSpan(hh, mm, ss) • DateTime dt = new DateTime(2020, 2, 29); • DateTime dt = new DateTime(2023, 1, 31); • DateTime dt = new DateTime(2023, 10, 5); • DateTime dt = new DateTime(2023, 10, 5, 14, 0, 0);
• TimeSpan(dd,hh,mm,ss) DateTime newDt = [Link](1); DateTime newDt = [Link](1); DateTime newDt = [Link](2.5); //2 days 12 hours DateTime newDt = [Link](3.5); //Add 3h 30 min
• TimeSpan(dd,hh,mm,ss,ms) [Link](newDt); // 2/28/2021 [Link] AM [Link](newDt); //2/28/2023 [Link] AM [Link](newDt); // 10/7/2023 [Link] PM [Link](newDt); //10/5/2023 [Link] PM
• var s = new TimeSpan(cntrctr);
5- [Link](dminutes); 6- [Link](dseconds); 7- [Link](dms); 8- [Link](timeSpan); 9- [Link](DateTime value);
• Adds minutes to the DateTime, retn DT • Adds seconds to the DateTime retn DT • Adds milliseconds to the DateTime retn DT. • add timespn to dt obj retrn DT • Compares two dates return -1, 0, 1 in int
• DateTime dt = new DateTime(2023, 10, 5, 14, 30, 0); • DateTime dt = new DateTime(2023, 10, 5, 14, 30, 0); • DateTime dt = new DateTime(2023, 10, 5, 14, 30, 0); • var dt = new DateTime(2023, 10, 5) • t1 < t2→ -1 • t1 == t2→0 • t1 > t2→ 1
DateTime newDt = [Link](45); //Add 45 min DateTime newDt = [Link](45); DateTime newDt = [Link](1500); //1.5 sec [Link](new TimeSpan(1, 0, 0, 0) • DateTime dt1 = new DateTime(2023, 10, 5);
[Link](newDt); // 10/5/2023 [Link] PM [Link](newDt); // 10/5/2023 [Link] PM [Link](newDt); //10/5/2023 [Link].500 PM //10/6/2023 [Link] AM DateTime dt2 = new DateTime(2023, 10, 6);
int result = [Link](dt2);
[Link](result); // Output: -1
10- [Link](DateTime value); 11- [Link](); 12- [Link](); 13- [Link](); 14- [Link]();
• Checks if two DateTime instances are equal. (sme obj) • cnvrt DateTime 2 str usin default frmt ret string • cnvrts DT 2 short time retrn string.(hh:mm AM/PM) • cnvrt DT 2 long time retrn string.(hh:mm:ss AM/PM) • cnvrt DT 2 short date, retrn string (dd-MM-yyyy)
• DateTime dt1 = new DateTime(2023, 10, 5); • DateTime dt = new DateTime(2023, 10, 5, 14, 30, 0); • DateTime dt = new DateTime(2023, 10, 5, 14, 30, 0); • DateTime dt = new DateTime(2023, 10, 5, 14, 30, 0); • DateTime dt = new DateTime(2023, 10, 5);
DateTime dt2 = new DateTime(2023, 10, 5); [Link]([Link]()); [Link]([Link]()); [Link]([Link]()); [Link]([Link]());
bool isEqual = [Link](dt2); // Output: "10/5/2023 [Link] PM" (culture-dependent) //Output: "2:30 PM" // Output: "[Link] PM" // Output: "10/5/2023"
[Link](isEqual); // Output: True
14- [Link](); 15- [Link](); 16- [Link](); 17- [Link](DT value);
• cnvrt DT 2 long date ret str.(day, month, dd, yyyy) • cnvrts local DT 2 UTC if (kind: locl/unspcifid) ret DT. • cnvrt Utc tym to locl comp tym if tym is alrdy in Utc • it calclte difrnc btwn 2 date & retun TimeSpan
• DateTime dt = new DateTime(2023, 10, 5); • DateTime localTime = [Link]; • DateTime localTime = [Link]; • DateTime date1 = new DateTime(2023, 6, 15);
[Link]([Link]()); DateTime utcTime = [Link](); DateTime utcTime = [Link](); DateTime date2 = new DateTime(2023, 6, 10);
// Output: "Thursday, October 5, 2023" [Link](utcTime); //comptr tym 2 utc [Link]([Link]()); TimeSpan difference = [Link](date2);
[Link](difference); // 5.[Link]
2- MATH CLASS
►DEFINITION-------------------------------------------------- (1) ►Math is a predfnd sttc cls in system namespace with sttc mthds 2 perform mathematical operations
1. DEFINITION-------------------------------------------------- (2) ► representation of characters into numbers or any other format is encoding, ►encoding functionality present is [Link] cls & [Link] namespace.
2. ASCII------------------------------------------------------------ (4) ►american standard code for information interchange, ►older way to represent chars in numbers, ►support only english characters, ►almost all keyboard characters were included (128 chars, 7bit(1byte) for each char)
3. UNICODE------------------------------------------------------ (4) ►universal code, ►newer way to represent chars in numbers, ►supports all international language chars with ascii, ►almose 145k chars available & almost every char takes 2 bytes rarely 4 bytes
4. ASCII CODE ENCODING
1) Convert Characters to ASCII Code-------------------- (1) ►char chr = ‘A’; byte asciiChr = (byte)chr; //64
2) Convert ASCII to Character----------------------------- (1) ►byte asciiChr = 64; char chr = (char)asciiChr; // ‘A’
3) Convert Between byte[] (ASCII code) & String
1- byte[] of numbers---------------------------------------(2) ►any byte[] num you have or created ex: byte[] x = new byte[]{56,43,87,92}, ►byte[] of 0-127 filld via for loop, byte[] byte = new bytes[128]; for(int i =0; i<128, i++){ bytes[i] = i; } // bytes = [0,1,2,…127]
2- Converting byte[] to String--------------------------- (2) ►[Link] cls has predfnd sttc mthd, ►[Link](byte[]);→retrn string, ascii is prop, ► ex: byte[] x = new byte[]{56,43,87,92} string s = [Link](x) //s= 8+W\
3- Output As Strict ASCII------------------------------- (2) ►some ascii char r nt suprtd recntly 2 avoid thm v cn us consol prop like: [Link] = [Link]; ►this means v hv to print all the chars as ascii format only
4- Converting String to byte[]--------------------------- (2) ►[Link] cls has predfnd sttc mthd, ►[Link](string);→retrn byte[], ascii is prop, ►string s = "how are you ?"; byte[] b = [Link](s);//[104,111,119,32,97,114,101,32,121,111,117,32,63]
5. UNICODE ENCODING
1) How To Write Sting Using Unicode
1- Direct Copy---------------------------------------------- (1) ”
►u cn dirctly copy any text or chars in other language ans paste as a string literals, ►string s = “; فراز cw(s); →watch using debuggin: فراز
2- By Writing Using Unicode---------------------------- (1) ►u cn put unicod in the string literals prefxin it wid \u for each unicod, ►string s = "\u0641\u0631\u0627\u0632" cw(s); →watch using debuggin فراز
2) Convert Char to Unicode--------------------------------- (3) ►convrt chr to int, ►ensure to add U+ string and int value, ►format specifier {var:X4} to ensure 4 digit
1. 2. [Link] NAMESPACE----------------------------(1) ►[Link] namespace contains various classes to operate on files on the system and manipulate them.
3. CLASSES OF [Link]---------------------------- (11) ►File, ►FileInfo, ►Directory, ►DirectoryInfo, ►DriveInfo, ►FileStream, ►StreamWriter, ►StreamReader, ►BinaryWriter, ►BinaryReader, ►FileNotFoundException
5.1- FILE CLASS
1. 2. DEFINITION----------------------------------------------(2) ►file is sttc cls tht manplt files, ►it is present in [Link] namespace hence v hv 2 import it by using.
3. FILE PATH------------------------------------------------ (3) ►file path is str having “driveName/folderName/fileName”, ►file path contening singl ‘\’ r cnvrtd into doubl ‘\\’ 2 avoid escp seqnc. ►file path cntening singl ‘\’ cn be usd as it is with verbatim str whch starts with @ “”.
METHODS OF FILE CLASS (all static)
1- [Link](fileNameWidPath); 2- [Link](fileNameWidPath) 3- [Link](fileNmeWidPath, psteFileNameWidPath) 4- [Link](fileNmeWidPath, mov/renmeFileNameWidPath) 5- [Link](fileNameWidPath)
• crets & opn / ovrwrite & opn file @ a spcfc path. • chks file exists or nt retrn bool true if exists else false. • it wil copy file in same or difrnt foldr withn sme • it cn eithr renme & move a fyl 4m 1 location 2 • file @ prticulr path gets deleted
• usin ths mthd files r open so v hv 2 clos is by .Close(); • bool x = [Link](@“D:\practice\[Link]”); drive. anthrBt wthn sme drive. • [Link](@ “D:\practice\india2”);
• [Link]("D:\\practice\\[Link]").Close(); [Link](x); // true • file path here is where to copy the file. • 2 jst renme, mov fyl wthn sme foldr wid dif nme
• if file wid sme nme alredy prsnt, it gts overwritten. • [Link](@“D:\practice\[Link]”, • if wnt 2 move fyl in anthr foldr giv tht foldr nme.
@“@D:\practice\[Link]”); • if wnt 2 renme & move do prvious 2 options.
6- [Link](fylNmeWidPth, strText) 7- [Link](fileNameWidPath) 8- [Link](fylNameWidPth, Str[]/list) 9- [Link](fileNameWidPath) File.(Open, OpenRead, OpenWrite)
• fyl if nt prsnt gts cretd and text is writn on it. • read txt 4m fle & retun in string. • if fyl nt prsnt, gts [Link] mem is aded in new lyn • it reads all lines and retrn a string array of content. • learn it in file stream cls
• string fileName = @"D:\practice\[Link]"; • string read = [Link](@“D:\practice\[Link]”); • var filePath = @ “D:\practice\[Link]”; • string[] s = [Link](@ • [Link](path, FileMode, FileAccess)
string text = "india is my country"; Cw(n); var animals = new list<string>(){“a”, “b”, “c”}; “D:\practic\[Link]”);
[Link](fileName,text); [Link](filePath, animals); • use foreach to cw.
10- [Link](path, FileMode, FileAccess) 11- [Link](path) 12- [Link]( string path)
• Opens the file in specified file mode with specified file access • Opens the file in ‘Open’ mode and returns a new • Opens the file in ‘OpenOrCreate’ mode and returns
permission and returns a new object of FileStream type. object of FileStream type. an object of FileStream type.
5.2FILEINFO CLASS
1. 2. DEFINITION--------------------------------------------- (2) ►it is a instance cls in [Link], ►using this cls u cn manipult the files like create, open, copy, move, delete, ►2 use this class u ned 2 cret an obj of this cls usin: FileInfo obj = new FileInfo(fileNamePath);
3. FILEINFO CLASS OBJECT---------------------------(2) ` ►every fileinfo cls obj point to its file, it means for every file there is a fileinfo obj tht contains path of tht file give in constructor
4. ADVANTAGE OVER FILE CLASS------------------ (2) ` ►with file cls 4 evry mthd v hv 2 mntion File cls & most of tym source path, here source pth is already tken by obj & no ned 2 mention cls name, ►4 one tym oprtn use file cls for multiplr oprtion use fileinfo
INSTANCE METHODS OF FILEINFO CLASS
1- [Link]() 2- [Link](paseFileNamePath, bool overwrite) 3- [Link](mov/renmeFileNameWidPath) 4- [Link](); 5- [Link](FileMode, FileAccess)
• it create a file & also opn it, so v hv 2 clos it. • it wil copy file in same or difrnt foldr wthn sme drive. • it cn renme/mov fyl wthn same drive 4m 1 foldr 2 • [Link](); will delete the file of its reference path. ►Opens the file at specified file mode and specified
st
• 1 v hv 2 cret fileInfo obj. • it wil cret anthr instnc & retrn the same othr file access permission & creates and returns an object
• FileInfo x = new FileInfo(@ “D:\practice\[Link]”); • FileInfor y = [Link](@ “D:\practice\[Link]”); Retn void with prvious file path copies to ths obj. of FileStream class that can write / read the file data.
• [Link]().Close(); • optional bool if mentioned true, if file exist in • if wnt 2 jst renme, mov fyl wthn sme foldr wid dif
►Creates the file at specified path & creates and returns an destination will get overwrite, else exception nme 5- obj.(open, opentext,openread, openwrite)
object of FileStream class with ‘Create’ mode, which can write ► Copy d fyl in2 new destintion path. It retn an object • if wnt 2 move fyl in anthr foldr giv tht foldr nme. • learn it in file stream class.
data to the same file of FileInfo cls, that represents the newly created fyl. • if wnt 2 renme & move do prvious 2 options.
6- [Link]( ) 7- [Link]( ) 8- [Link]( ) 9- [Link]( ) 10- obj. OpenText( )
►Opens the file in 'Read' mode & creates and returns an ►Opens the file in 'OpenOrCreate' mode & creates ► Opens the file in 'Create' mode & creates and ► Opens the file in 'Append' mode & creates and ► Opens the file in 'Open' mode & creates and
object of FileStream class that can read the file data. and returns an object of FileStream class that can returns an object of StreamWriter class that can write returns an object of StreamWriter class that can returns an object of StreamReader class that can
read the file data. text to the file write the appended text to the file read text from the file.
PROPERTIES OF FILEINFO CLASS (provides additional info about files)
1- [Link] 2- [Link] 3- [Link] 4- [Link] 5- [Link]
• string prop, get name of the file • string prop, gets full name as path of the file • string prop, gets folder name in whch file is present • bool prop, if exist gets true else false • string prop, gets extension name of the file
• FileInfo blurr = new • string fullName = [Link]; • string folderName = [Link]; • bool x = [Link]; • string extensionName = [Link];
FileInfo(@”D:\practice\[Link]”); • string fullName = [Link]; [Link](folderName); //D:\ • bool x = [Link]; [Link](extensionName); //.txt
• string name = [Link]; [Link](fullName); //D:\practice\ practice [Link](x); //true
[Link](name); //[Link] [Link]
6- [Link] 7- [Link] 8- [Link] 9- [Link];
• byte prop gets size of file in bytes. • DateTime prop gets last modification time • DateTime prop gets creation time of the file • DateTime prop gets last time of the file handling
• byte size = [Link]([Link]); OR • DateTime t = [Link]; • DateTime ct = [Link];
var size = [Link]; [Link]([Link]()); [Link]([Link]());
[Link](size); //15 // 06-05-2025 [Link] // 06-05-2025 [Link]
5.3- DIRECTORY CLASS
1. 2. DEFINITION------------------------------------------------- (1) ►predefnd sttc cls in [Link] through which you can manipulate directories (folders)
3. LEARN THROUGH TASK-------------------------------- (7) ►cret foldr “countries”in a foldr, ►cret foldr “india”, “UK”, “USA” in country foldr, ►cret 3 files:txt “capital”, “sports”, “population” in each country fldr, ►mov/renme countries foldr as world, ►lst fyls of world,
►list foldr of world folder, ►delete world foldr including its fyls & subfyls
METHODS OF DIRECTORY CLASS
1- [Link](dirctryNameWidPath) 2- [Link](dirNameWidPath,mov/renmeDirNmeWidPath) 3- [Link](dirctryNameWidPath, pttrn) 4- [Link](directoryNameWidPath) 5- [Link](dirNameWidPath, bool recursv)
• it wil cret foldr @ gvn path, lst itm is name • it cn renme/mov dir wthn same drive 4m 1 locat 2 • all files paths are return as a string array. • all director paths are return as string array • if dir is empty only path will delete is as bool is opt
• [Link](@"D:\practice\countries"); othr • string[] files = • string[] folders = • if dir conten somthin (path, true) will delte it with
• for cretin sub foldr give cmplt path @ lst give foldr • 2 jst renme, mov dir wthn sme path wid dif nme [Link](@"D:\practice\world"); [Link](@"D:\practice\world"); its content else v get excption sayin dir conten
Name u wnt to cret. • 2 move dir in anthr loc giv tht location path. somthin.
• for creting files in sub folder u cn use File/FileInfo • if wnt 2 renme & move do prvious 2 options. // D:\practice\world\[Link] // D:\practice\world\india 6- [Link](dirNameWidPath)
• [Link](@"D:\practice\countries"); • [Link](@"D:\practice\countries", D:\practice\world\[Link] D:\practice\world\UK • return true if directory exists else false.
•[Link](@"D:\practice\countries\india"); @"D:\practice\world"); D:\practice\world\[Link] D:\practice\world\USA • boole exists =
•[Link](@"D:\practice\countries\USA"); [Link](@"D:\practice\world"); //false.
• [Link](@"D:\practice\countries\[Link]").Close(); • additionally v cn gv search pattern in second arg
• [Link](@"D:\practice\countries\[Link]").Close(); , “*.txt”→meaning *(all) files tht have .text
•[Link](@"D:\practice\countries\
[Link]").Close();
1. 2. DEFINITION------------------------------------------------ (1) ►predefnd instance cls to manipulate and acess info about drives of the hard disk.
3. DRIVEINFO CLASS OBJECT----------------------------(2) ►evry drive hv a obj reference through whch it is accessed, ►DriveInfo obj = new DriveInfo(“driveName:”); ►DriveInfo x = new DriveInfo(“d:”);
PROPERTIES OF DRIVEINFO CLASS
1- [Link] 2- [Link]; 3- [Link] [Link] 5- [Link]/1024/1024/1024 [bytes 2 gb]
• string type prop gets drive name. • DriveType typ prop gets whthr drive is fixd or rmovbl • string typ prop gets drive name. • object typ prop gets roo directory • long typ prop gets totl size of drv in bytes. V hv 2
• string name = [Link]; • DriveType fixRemove = [Link]; • string volumeLabel = [Link]; • object root = [Link]; cnvrt in into kb, mb, gb by dividing it by 1024
[Link](x); // D:\ [Link](fixRemove); // Fixed [Link](volumeLabel); //New Volume [Link](root); //D:\ • long size = [Link] / 1024 / 1024 / 1024;
[Link](size); // 300
[Link]
• long typ prop gets available free spce in bytes. We
hv 2 cnvrt it in kb, mb, gb by dividing by 1024
• long freeSpace = [Link] /1024/1024/ 1024;
[Link](freeSpace); //300
5.6- FILESTREAM CLASS
1. 2. DEFINITION--------------------------------------------------(3) ►predfnd instanc cls which alows 2 write strings on file directly and read the string from file directly, ►it does all the conversion from byte[]→string or string→byte[] internally., ►works only with text files
3. OBJECT OF STREAMWRITER CLASS---------------(4) ►StreamWriter obj = new StreamWriter(filePath); ►new StreamWriter(filepath, bool append);, ►new StreamWriter(filePath, bool append, Encoding encoding);, ►new StreamWriter(Stream stream);[cret wrtr 4 crnt strm]
4. OBJECT OF STREAMREADER CLASS-------------- (2) ► StreamReader obj = new StreamReader(filePath), ►new StreamReader(Stream stream)
METHODS OF STREAMWRITER METHODS OF STREAMREADER
1- [Link](“text”) 2- [Link](“text”) 1- [Link](); 2- [Link](emptyBuffr[],indxno2kep, chr2read) 3- [Link]()
►directly writes text on file with nw lyn, Write(wtht) ►writes without going to next line ►reads text from start to end retrn string. ►char[] buffr = new char[char2read]; ►read 1 line from the text and return as string
►after writing [Link](); [Link](); ►after writing [Link](); [Link](); ►after reading, [Link]();, [Link](); ►int char_left = [Link](buffr,0,10); ►StreamReader re = new StreamReader(path);
►use using statemnt to avoid put close, and dispose ►use using statemnt to avoid put close, and dispose ►use using statemnt to avoid put close, and dispose ►buffr=empty[], 0=index @ 10 chr info is kept, 10= ►string s = [Link]();
►[Link](s);
chars to read ►after reading, [Link]();, [Link]();
►string s = new string(buffr); cw(s) ►use using statemnt to avoid put close, and dispose
►cursor waits at10th char reapeat code to reade nxt 10
►this methd also return int charRead so use in loop
►after reading, [Link]();, [Link]();
►use using statemnt to avoid put close, and dispose
6- SERIALIZATION & DESERIALIZATION
1. 2. SERIALIZATION-------------------------------------------- (1) ►conversion of object (any obj, instance of cls) into format (json format, xml, bin) so tht it can be easily stord, sent
3. DESERIALIZATION----------------------------------------(1) ►conversion of json, xml format data back into an object, instance of cls
4. JSON SERIALIZATION
1) Namespace To Use---------------------------------------- (1) ►using [Link], ►if error occurs in using statement v hv 2 add reference to dll file, Rclick on project→Add→Reference→Assembly(expnd it)→check on [Link]
2) Class For Json Serialization---------------------------- (1) ►in [Link] namespace there is a predefined class JavaScriptSerializer. This cls is used to serialize an obj into json and json into obj.
3) Json Format------------------------------------------------(1) ►Object: { Field1 = value1; Field2 = value2; Field3 = value3 }, ►Json data: { “Field1”: “value1”, “Field2 : “value2”, “Field3”: “value3”} if value is number “” not required.
JSON SERIALIZATION
1- make your class serializable [Serializable] 2- make object of your serializable class in main 3- make object of serialization class 4- serialize class object using serialize method 5- write json data to a file to check conversion
[Serializable] Var customer = new Customer(); 1- import [Link] [Link](classObject); → string filePath = @“D:\practice\[Link]”;
public class Customer [Link] = 1; 2- add reference to [Link] dll • obj: JavaScirptSerializer object → StreamWriter x = new StreamWriter(filePath);
{ [Link] = “Nancy”; 3- make object of JavaScriptSerializer class. • classObject: any object of your serializable class → [Link](jsonData);
public int CustomerId {get; set;} [Link] = 20; • this method returns string → [Link]();
public string CustomerName{get; set;} → var javaSerializer = new JavaScriptSerializer();
public int Age {get; set;} Customer → string jsonData = [Link](customer);
} CustomerId 1
CustomerName “Nancy”
• [Serializable] ensures that this class obj can be Age 20
conveted into any other format like xml, bin, json.
JSON DESERIALIZATION
1- get json data in string form 2- deserialize data into class object 3- confirm deserialization using new object
• get it through api or from any file. In this case file. [Link](string data, typeof(ClassName)); [Link]([Link]);
→ string filePath = @“D:\practice\[Link]”; • make new or use old JavaScriptSerializer object [Link]([Link]);
→ var reader = new StreamReader(filePath); • string data: jason data in string format [Link]([Link]);
→ string jsondata = [Link](); • we cnt use cls name as a prmtr hence use typeof(CN)
• this mthd retrns type is object. We hv to type cast it in • if they matches with customer1 than deserialization
obj of our clss (data, typeof(ClsNme)) as ClassName; done successfully.
Customer customer2 = [Link]
(jsondata, typeof(Customer)as Customer):
7- EXCEPTION HANDLING
1. TYPES OF ERRORS IN PROGRAMMING
1) Compile Time Errors------------------------------------- (1) ►err due 2 syntactcl mistks eg. Missin semicln, str in nt doubl quots, braces nt closd., ►cn b easily tackld
2) Run Time Error------------------------------------------- (1) ►err nt at a tym of cmpltion but execution. ,►occur due 2 wrng implmnt of logic, wrng i/p supplied, missing resourcs etc., ►thes errs trmnt prgrm abrptly as furthr code in the progrm dos nt run
3) Exceptions-------------------------------------------------- (3) ►Excption is a clss, ►whn runtym err occur, bsed on typ of err an exception objct is cretd tht trmint furthr code execution unless hndled, ►4 evry typ of runtym err ther is a excption cls derivd 4m parent excption cls Exception
2. EXCEPTION CLASS
1) Definition ---------------------------------------------------(1) ►Parent of all exception clss it contain all logc 4 abnrml trmntion & hv a virtual readonly prop “message” 2 display err msg evry chld cls cn ovrrd thid prop
2) Child Classes of Exception Class
1- ApllicationException---------------------------------- (1) ►non fatal errs, progrmr cn mke thr own excption
2- SystemException--------------------------------------- (3) ►fatal errs, automtcly gnrtd by clr, ►all excption we gnrly see like IndexOutOfBound, FormatException, ArithmaticException(DivideByZeroExcp, OverFlowException) are present in this., ►thy cn ovrrd message prop of excp
3. SYSTEM EXCEPTION HANDLING
1) Definition ---------------------------------------------------(1) ►proces of stoping abnrml trmintion of prgrm, giv usr frndly messge, take corrective actions(rollback) when runtym err occurs.
2) Syntax -------------------------------------------------------(1) ►Try{ statements;} Catch(ExceptionClassName variable){statements;} Finally{statements}
3) Try block---------------------------------------------------- (1) ►statemnts whch cn cause runtym err, statemnts whch dosnt requir execution whn runtym err occur
4) Catch block------------------------------------------------- (1) ►statements whch should execute only whn thr is a runtym err occur, ►v cn put multple catch blocks for mltpl runtym err., ►first put catch 4 obvious errs then at last put one (Exception ex) for all kind of err.
5) Finally block------------------------------------------------(2) ►compulsory execution., ►statements in finally block will execute irrespective of whether the tuntym err occur or not, usually used to cleanup the resources.
4. COMMON TYPES OF SYSTEM EXCEPTION
1) DivideByZeroException
1-Defnition------------------------------------------------ (1) ►Occurs when attempting to divide a number by zero,
2-Handling DivideByZeroException----------------- (1) ►try{int a = 10; int b = 0; int c = a/b;} catch(DivideByZeroException ex){cw([Link]);} //attempt to divide by zero
3-Best Practices------------------------------------------- (2) ►precheck denomintr for zero using if, ►use single, double type as 10.0/0.0 doesn’t throw instead return infinity or NaN.
2) FormatException
1-Definition------------------------------------------------ (2) ►frmt excp occur whn string cnt b cnvrtd in2 a numrc typ dur 2 invld formt(ltrs, symbl, spcs),►gnrl datatyp cnvrsn whr source formt is incomptbl ►conversion error
2-Handling FormatException------------------------- (1) ►string s “123a”; try{int b = Convert.ToInt32(s);} catch(FormatException fe){cw([Link]);} // Input string was not in a correct format.
3-Best Practices------------------------------------------- (2) ►use tryparse 4 saf cnvrsn, ►catch formt excption separately 4m othr excption.
3) IndexOutOfRangeException
1-Definition----------------------------------------------- (1) ►occurs whn attempting 2 access array or iterable with invalid index no. like -ve index or index>= length of iterable.
2-Handling IndexOutOfRangeException----------- (1) ►string[] fruits = { "Apple", "Banana", "Mango" };try{ [Link](fruits[3]); // Risky access } catch (IndexOutOfRangeException ex){ [Link]([Link]); } // Index was outside the bounds of the array
3-Best Practices------------------------------------------- (3) ►Precchk index:if (index >= 0 && index < [Link]){ BankAccount selectedAccount = accounts[index];}, ►use foreach instead of for, ►combine with othr exception like format exception.
4) NullReferenceException
1- Definition------------------------------------------------ (2) ►occurs whn attempting 2 access members of a cls obj (mthd, prop, indxr) through refvar that is null, passing uninitialized null object to methd, ►when null obj of any kind is used.
2- Handling NRE------------------------------------------(1) ►string[] names = null; try{ [Link]([Link]); } catch (NullReferenceException ex){ [Link]("Error: Object is null!"/[Link]); }//
3- Best Practices------------------------------------------- (3) ►validate be4 use using if (obj != null) else{throw new}, ►use ?. operator for safe access: obj?.membr;→retn null no exception, ►re throw, if want to notify to main method
5) ArgumentNullException
1- Definition ----------------------------------------------- (1) ►whn v dnt wnt any mthd prmtr 2 recev a null val then v use if statemnt 2 vldat if prmtr val is null or not , if null thn v throw argmnt null excption, ►tho it is builtin cls but nt thrown by clr v hv 2 throw it manually
2- Example------------------------------------------------- (1) ►void PrintUserName(string userName) { [Link]([Link]()); } PrintUserName(null) // ❌ Throws NullRefEx if userName is null
3- Handling In Method---------------------------------- (1) ►void PrintUserName(string userName) { if (userName == null) throw new ArgumentNullException(nameof(userName)); [Link]([Link]()); }
4- Handling In Caller-------------------------------------(1) ►try { PrintUserName(null); } catch (ArgumentNullException ex) { [Link]($"Error: {[Link]}"); } // Output: "Value cannot be null. Parameter name: userName"
6) ArgumentOutOfRangeException
1- Defintion ----------------------------------------------- (1) ►Thrown when an argument's value falls outside the acceptable range for a method.
2- Example ------------------------------------------------ (1) ►supos u promp usr 2 entr numbr betwn 1-10 for mthd tht chks numbr btween 1-10
3- Handling In Method---------------------------------- (1) ►static void CheckNumber(int num) { if (num < 1 || num > 10) throw new ArgumentOutOfRangeException(); }
4- Handling In Caller------------------------------------ (1) ►static void Main() { try { CheckNumber(15); // Try changing this number } catch (ArgumentOutOfRangeException ex) {CW([Link]); CW([Link]); CW([Link]);} }
Definition--------------------------------------------------- (1)
Syntax------------------------------------------------------- (1)
Rules--------------------------------------------------------- (3)
Working----------------------------------------------------- (1)
Used When------------------------------------------------- (1)
Types-------------------------------------------------------- (1)
Special Points---------------------------------------------- (1)
DEFINITION------------------------------------------------- ()
SYNTAX------------------------------------------------------- ()
ACCESSING ELEMENTS-------------------------------- ()
TYPES---------------------------------------------------------- ()
►
►
►
►
►
►
►
Implicit Tuple With Named Fields-------------------- (1)