c# markdown cheatsheet
Published: Friday, January 1, 2016
This is a post where I wanted to add a bunch of mark down but I got this error
wyam skipping file due to not having published metadata
C# Notes
Yield
allows each iteration in a foreach-loop be generated only when needed (In this way it can improve performance)
Used in methods that returns these types...
IEnumerable
(without any angle brackets) {ref. System.Collections } , orIEnumerable<Type>
with a type parameter in the angle brackets {ref. System.Collections.Generic }
Yield Return
- similar to a return statement followed by a
goto
to the yield statement in the next iteration of the foreach - See next paragraph
yield return new ValidationResult("Error Message")
DataAnnotations and IValidatableObject - (yield example)
using System.ComponentModel.DataAnnotations;
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var pIncome = new[] { "Income" };
if(Income<0) { yield return new ValidationResult("Income cannot be negative", pIncome); }
var pName = new[] {"Name"};
if (Name.Length > 40) { yield return new ValidationResult("Name cannot be such huge in length", pName); }
var pBDate = new[] {"BirthDate"};
if (BirthDate > DateTime.Now) { yield return new ValidationResult("Sorry Future Date cannot be accepted.", pBDate); }
}
[Required]
public bool Enable { get; set; }
[Range(1, 5)]
public int Prop1 { get; set; }
[Range(1, 5)]
public int Prop2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (this.Enable)
{
Validator.TryValidateProperty(this.Prop1,
new ValidationContext(this, null, null) { MemberName = "Prop1" }, results);
Validator.TryValidateProperty(this.Prop2,
new ValidationContext(this, null, null) { MemberName = "Prop2" }, results);
// some other random test
if (this.Prop1 > this.Prop2)
{
results.Add(new ValidationResult("Prop1 must be larger than Prop2"));
}
}
return results;
}
// http://stackoverflow.com/questions/3400542/how-do-i-use-ivalidatableobject
sources
Other
without RemoveEmptyEntries
string value = "shirt\rdress\r\npants\r\njacket";
char[] delimiters = new char[] { '\r', '\n' };
string[] parts = value.Split(delimiters);
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine(parts[i]);
}
with RemoveEmptyEntries
string value = "shirt\rdress\r\npants\r\njacket";
char[] delimiters = new char[] { '\r', '\n' };
string[] parts = value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine(parts[i]);
}
This page is statically generated by Wyam at build time.