Created
May 10, 2023 07:19
-
-
Save zhangr4/a8427a0a3ac0653a0a737651a1785532 to your computer and use it in GitHub Desktop.
c# snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges | |
#region Indexable Example | |
//System.Index | |
// use '^' operator: means read from end = true | |
// '^' operator requires type is countable and have indexer: | |
interface IIndexable<T>{ | |
public int Length { get; } // need public property 'Length', which has get access | |
public T this[int index] { get; } // need public indexer, which takes a single int as the argument. | |
//or need public indexer, which has parameter type of System.Index | |
// public T this[Index index] { get; } | |
} | |
class X : IIndexable<string> | |
{ | |
private int _length = 10; | |
public int Length{ | |
get => _length; | |
} | |
public string this[int index] => "asd"; | |
} | |
var x = new X(); | |
Console.WriteLine(x[^1]); | |
#endregion | |
#region Rangeable example | |
//System.Range | |
// use range operator x..y. It is a binary infix operator that accepts two expressions | |
// '..' operator requires type is countable and has slice method | |
// for range operator x..y, x is included and y is excluded. .. means all, y can be applied with hat operator '^' | |
public interface IRangeable<T>{ | |
public int Length { get; } // need public property 'Length', which has get access | |
public IRangeable<T> Slice(int start, int end);// need public member Slice, which takes two int as argument | |
// or need public indexer, which has parameter type of System.Range | |
// public T this[Range range] { get; } | |
} | |
public class Y : IRangeable<string>{ | |
public int Length{ get => 10; } | |
public IRangeable<string> Slice(int start, int end){ | |
return new Y(); | |
} | |
} | |
var y = new Y(); | |
var result = y[..]; | |
#endregion | |
/* | |
* could use range operator replace String.Substring() method | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment