├── global.json ├── RecordsNaoExistem.cs ├── TiposNaoExistem.cs ├── GlobalSuppressions.cs ├── Program.cs ├── PrimaryConstructorNaoExiste.cs ├── ValoresDefaultArgumentosNaoExistem.cs ├── GotoExiste.cs ├── DiscardsNaoExistem.cs ├── AsyncNaoExiste.cs ├── TuplasExistem.cs ├── TryCatchNaoExiste.cs ├── dotnetnaoexiste.csproj ├── YieldDesempenho.cs ├── OperadoresNaoExistem.cs ├── AsyncDesempenho.cs ├── YieldNaoExiste.cs ├── NullableNaoExiste.cs ├── LICENSE.txt ├── .vscode ├── launch.json └── tasks.json ├── ObjetosNaoExistem.cs ├── dotnetnaoexiste.sln ├── UsingNaoExiste.cs ├── PatternMatchersNaoExistem.cs ├── LinqNaoExiste.cs └── .gitignore /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "allowPrerelease": true, 4 | "rollForward": "latestMajor" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /RecordsNaoExistem.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste.Records; 2 | 3 | record Produto(int Id, string Nome); 4 | 5 | record struct Cor(string Nome); 6 | 7 | readonly record struct CorImutavel(string Nome); 8 | -------------------------------------------------------------------------------- /TiposNaoExistem.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace NonEcsiste.TiposNaoExistem; 4 | 5 | public class T 6 | { 7 | static Simples Foo() 8 | { 9 | var simples = JsonConvert.DeserializeObject("{ a: 1, b: 2 }"); 10 | return simples; 11 | } 12 | } 13 | 14 | public class Simples 15 | { 16 | public int a { get; set; } 17 | public int b { get; set; } 18 | } 19 | -------------------------------------------------------------------------------- /GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Code Quality", "IDE0051:Remove unused private members", Justification = "Example")] 2 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "Example")] 3 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "CS0168", Justification = "Example")] 4 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using NonEcsiste; 2 | using NonEcsiste.LinqNaoExiste; 3 | using NonEcsiste.Objetos; 4 | 5 | LinqNaoExiste.LinqToGiggio(); 6 | var gandhi = new Humano("Mahatma Gandhi"); 7 | WriteLine(gandhi.Nome()); 8 | var chimpanze = new Chimpanze(); 9 | WriteLine(chimpanze.Nome()); 10 | ReadLine(); 11 | var student = new PrimaryConstructor_Student(1, "Giovanni", new[] { 6.7m, 8.5m }); 12 | WriteLine(student.GPA); 13 | -------------------------------------------------------------------------------- /PrimaryConstructorNaoExiste.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste; 2 | 3 | public class PrimaryConstructor_Student(int id, string name, IEnumerable grades) 4 | { 5 | public PrimaryConstructor_Student(int id, string name) : this(id, name, Enumerable.Empty()) { } 6 | public int Id => id; 7 | public string Name { get; set; } = name.Trim(); 8 | public decimal GPA => grades.Any() ? grades.Average() : 4.0m; 9 | } 10 | -------------------------------------------------------------------------------- /ValoresDefaultArgumentosNaoExistem.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste; 2 | 3 | public class ValoresDefaultArgumentosNaoExistem 4 | { 5 | public void NaoExiste() 6 | { 7 | GetInt(); 8 | GetInt(1); 9 | GetInt(2); 10 | } 11 | public void NaoExiste2() 12 | { 13 | GetInt(100); // compilado fica assim 14 | GetInt(1); 15 | GetInt(2); 16 | } 17 | private static void GetInt(int i = 100) { } 18 | } 19 | -------------------------------------------------------------------------------- /GotoExiste.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste; 2 | 3 | public class GotoExiste 4 | { 5 | public static void GE() 6 | { 7 | WriteLine("antes do if"); 8 | if (DateTime.Now.Second > 30) 9 | goto meuLabel; 10 | WriteLine("depois do if"); 11 | goto meuOutroLabel; 12 | meuLabel: 13 | WriteLine("depois do primeiro label"); 14 | meuOutroLabel: 15 | WriteLine("depois do outro label"); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /DiscardsNaoExistem.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste; 2 | 3 | public class DiscardsNaoExistem 4 | { 5 | void DiscardReturn() 6 | { 7 | _ = RestornaString(); 8 | } 9 | 10 | static string RestornaString() => "a"; 11 | void DiscardOut() 12 | { 13 | Foo(out _); 14 | } 15 | void DiscardOut2() 16 | { 17 | int i = 2; 18 | Foo(out _); 19 | } 20 | 21 | static void Foo(out int i) 22 | { 23 | i = 1; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /AsyncNaoExiste.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste; 2 | 3 | public class AsyncNaoExiste 4 | { 5 | private readonly string file = null; 6 | async Task FooAsync() 7 | { 8 | int n = GetInt(); 9 | WriteLine(n); 10 | await Task.Delay(100); 11 | int o = GetInt(n); 12 | await Task.Delay(200); 13 | int p = GetInt(o); 14 | WriteLine(p); 15 | var text = await File.ReadAllTextAsync(file); 16 | WriteLine(text); 17 | } 18 | 19 | private static int GetInt(int i = 0) => DateTime.Now.Second + i; 20 | } 21 | -------------------------------------------------------------------------------- /TuplasExistem.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste; 2 | 3 | public class TuplasExistem 4 | { 5 | (int a, int b) Retorna() 6 | { 7 | var t = (a: 1, b: 2); 8 | return t; 9 | } 10 | 11 | public int Obtem1() 12 | { 13 | var (i, j) = Retorna(); 14 | return i + j; 15 | } 16 | 17 | static (int c, int d) Retorna2() 18 | { 19 | var t = (c: 1, d: 2); 20 | return t; 21 | } 22 | 23 | public int Obtem2() 24 | { 25 | var t = Retorna2(); 26 | var k = t.Item1; 27 | var l = t.Item2; 28 | return k + l; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /TryCatchNaoExiste.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste; 2 | 3 | public class TryCatchNaoExiste 4 | { 5 | public static void TC() 6 | { 7 | WriteLine("1"); 8 | try 9 | { 10 | WriteLine("2"); 11 | } 12 | catch (NullReferenceException nre) 13 | { 14 | WriteLine("3"); 15 | if (DateTime.Now.Second > 30) 16 | throw; 17 | else 18 | throw new Exception("erro", nre); 19 | } 20 | finally 21 | { 22 | WriteLine("4"); 23 | } 24 | WriteLine("5"); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /dotnetnaoexiste.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | net9.0 5 | NonEcsiste 6 | enable 7 | preview 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /YieldDesempenho.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste.YieldDesempenho; 2 | 3 | public class YieldDesempenho 4 | { 5 | public static IEnumerable Infinito(int start) 6 | { 7 | if (start < 0) 8 | throw new ArgumentException("Must be greater than 0.", nameof(start)); 9 | while (true) 10 | yield return start++; 11 | } 12 | } 13 | 14 | public class YieldDesempenhoMelhor 15 | { 16 | public IEnumerable Infinito(int start) 17 | { 18 | if (start < 0) 19 | throw new ArgumentException("Must be greater than 0.", nameof(start)); 20 | return InfinitoImpl(start); 21 | } 22 | private static IEnumerable InfinitoImpl(int start) 23 | { 24 | while (true) 25 | yield return start++; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /OperadoresNaoExistem.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste; 2 | 3 | public class OperadoresNaoExistem 4 | { 5 | private static readonly Person pessoa = new Person(null); 6 | 7 | static void M() 8 | { 9 | var nome = pessoa?.Nome; 10 | // vira: 11 | if (pessoa != null) 12 | nome = pessoa.Nome; 13 | } 14 | 15 | static void N() 16 | { 17 | var outraPessoa = pessoa ?? new Person(null); 18 | // vira: 19 | if (pessoa == null) 20 | outraPessoa = new Person(null); 21 | } 22 | 23 | static void O() 24 | { 25 | Person maisOutraPessoa; 26 | if (pessoa is null) 27 | maisOutraPessoa = pessoa; 28 | else 29 | maisOutraPessoa = new Person(null); 30 | } 31 | 32 | record Person(string Nome); 33 | } 34 | -------------------------------------------------------------------------------- /AsyncDesempenho.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste.AsyncDesempenho; 2 | 3 | public class AsyncDesempenho 4 | { 5 | public static async Task DoAsync(int start) 6 | { 7 | if (start < 0) 8 | throw new ArgumentException("Must be greater than 0.", nameof(start)); 9 | await Task.Delay(100); 10 | WriteLine(start); 11 | } 12 | } 13 | 14 | public class AsyncDesempenhoMelhor 15 | { 16 | public Task DoAsync(int start) 17 | { 18 | if (start < 0) 19 | throw new ArgumentException("Must be greater than 0.", nameof(start)); 20 | return DoAsyncImpl(start); 21 | } 22 | public static async Task DoAsyncImpl(int start) 23 | { 24 | await Task.Delay(100); 25 | WriteLine(start); 26 | } 27 | 28 | public static Task FooAsync(int start) 29 | { 30 | return Task.Delay(100); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /YieldNaoExiste.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste; 2 | 3 | public class YieldNaoExiste 4 | { 5 | static IEnumerable Enum() 6 | { 7 | WriteLine("um"); 8 | yield return 1; 9 | WriteLine("dois"); 10 | yield return 2; 11 | WriteLine("tres"); 12 | yield return 3; 13 | } 14 | 15 | public static IEnumerable Infinito() 16 | { 17 | int i = 100 + DateTime.Now.Second; 18 | yield return i; 19 | while (true) 20 | { 21 | WriteLine(1); 22 | yield return i++; 23 | WriteLine(2); 24 | } 25 | } 26 | 27 | public static async IAsyncEnumerable InfinitoAsync() 28 | { 29 | int i = 100 + DateTime.Now.Second; 30 | yield return i; 31 | while (true) 32 | { 33 | WriteLine(1); 34 | await Task.Delay(1); 35 | yield return i++; 36 | WriteLine(2); 37 | } 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /NullableNaoExiste.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | namespace NonEcsiste; 3 | 4 | public class NullableNaoExiste 5 | { 6 | // ganha o atributo [NullableContext(2)] 7 | public static string? ProduceNullableString() => DateTime.Now.Second > 30 ? null : "string"; 8 | // ganha o atributo [NullableContext(1)] 9 | static void TakesStringAndNullableString(string text, /* [Nullable(2)] */ string? nullableString) => WriteLine(text); 10 | 11 | void ConsumesNullableStringWithNullCheck() 12 | { 13 | var nullableString = ProduceNullableString(); 14 | if (nullableString == null) 15 | return; 16 | TakesStringAndNullableString(nullableString, null); 17 | } 18 | void ConsumesNullableStringWithIsNullOrWhiteSpace() 19 | { 20 | var nullableString = ProduceNullableString(); 21 | if (string.IsNullOrWhiteSpace(nullableString)) 22 | return; 23 | TakesStringAndNullableString(nullableString, null); 24 | } 25 | } 26 | 27 | 28 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Giovanni Bassi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/bin/Debug/netcoreapp3.0/dotnetnaoexiste.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach", 24 | "processId": "${command:pickProcess}" 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /ObjetosNaoExistem.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste.Objetos; 2 | 3 | public abstract class Organismo 4 | { 5 | public abstract Reino Reino { get; } 6 | public abstract Ordem Ordem { get; } 7 | public abstract string Nome(); 8 | } 9 | 10 | public enum Reino { Animal = 1, Vegetal = 2 } 11 | public enum Ordem { Marsupialia, Chiroptera, Carnivora, Primata } 12 | 13 | public abstract class Animal : Organismo 14 | { 15 | public override Reino Reino { get; } = Reino.Animal; 16 | public override string Nome() => "Animal genérico"; 17 | } 18 | 19 | public abstract class Primata : Animal 20 | { 21 | public override Ordem Ordem { get; } = Ordem.Primata; 22 | public override string Nome() => "Primata genérico"; 23 | } 24 | 25 | public class Chimpanze : Primata 26 | { 27 | } 28 | 29 | public class Humano : Primata 30 | { 31 | private readonly string nome; 32 | 33 | public Humano(string nome) => this.nome = nome; 34 | 35 | public override string Nome() => nome; 36 | 37 | public static string NomeGenerico() => "pessoa"; 38 | } 39 | 40 | class Matematica 41 | { 42 | int zero = 0; 43 | public static int Soma(int a, int b) => a + b; 44 | public int SomaZero(int a) => zero + a; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/dotnetnaoexiste.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/dotnetnaoexiste.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/dotnetnaoexiste.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /dotnetnaoexiste.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29123.89 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "dotnetnaoexiste", "dotnetnaoexiste.csproj", "{3C523C96-50BD-4B86-8507-E249027F0AB0}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{38483F45-BCDB-49E6-A152-04728294338C}" 9 | ProjectSection(SolutionItems) = preProject 10 | .gitignore = .gitignore 11 | global.json = global.json 12 | EndProjectSection 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {3C523C96-50BD-4B86-8507-E249027F0AB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {3C523C96-50BD-4B86-8507-E249027F0AB0}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {3C523C96-50BD-4B86-8507-E249027F0AB0}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {3C523C96-50BD-4B86-8507-E249027F0AB0}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {4EFBC950-8B3A-4CFE-AF96-F031CF4B5B3E} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /UsingNaoExiste.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste; 2 | 3 | public class UsingNaoExiste 4 | { 5 | static void UsingDispose() 6 | { 7 | var buffer = new byte[] { 1, 2, 3 }; 8 | using (var ms = new MemoryStream()) 9 | { 10 | ms.Write(buffer, 0, 3); 11 | } 12 | } 13 | 14 | static void UsingStatementDipose() 15 | { 16 | var buffer = new byte[] { 1, 2, 3 }; 17 | using var ms = new MemoryStream(); 18 | ms.Write(buffer, 0, 3); 19 | } 20 | async Task AwaitUsingDipose() 21 | { 22 | await using (var enumerator = CreateAsyncDispoableAsync()) 23 | { 24 | while (await enumerator.MoveNextAsync()) 25 | { 26 | WriteLine(enumerator.Current); 27 | } 28 | } 29 | } 30 | async Task AwaitUsingStatementDipose() 31 | { 32 | await using var enumerator = CreateAsyncDispoableAsync(); 33 | while (await enumerator.MoveNextAsync()) 34 | WriteLine(enumerator.Current); 35 | } 36 | IAsyncEnumerator CreateAsyncDispoableAsync() 37 | { 38 | var stream = CreateStreamAsync(); 39 | return stream.GetAsyncEnumerator(); 40 | } 41 | async Task ReadStreamAsync() 42 | { 43 | WriteLine("um"); 44 | await foreach (var line in CreateStreamAsync()) 45 | WriteLine(line); 46 | WriteLine("dois"); 47 | } 48 | 49 | static async IAsyncEnumerable CreateStreamAsync() 50 | { 51 | using var sr = new StreamReader("path"); 52 | while (!sr.EndOfStream) 53 | yield return await sr.ReadLineAsync(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /PatternMatchersNaoExistem.cs: -------------------------------------------------------------------------------- 1 | namespace NonEcsiste; 2 | 3 | public class PatternMatchersNaoExistem 4 | { 5 | static string Classify(double measurement) => measurement switch 6 | { 7 | < -4.0 => "Too low", 8 | > 10.0 => "Too high", 9 | double.NaN => "Unknown", 10 | _ => "Acceptable", 11 | }; 12 | 13 | 14 | private static string ClassifyCompiled(double measurement) 15 | { 16 | if (!(measurement < -4.0)) 17 | { 18 | if (!(measurement > 10.0)) 19 | { 20 | if (double.IsNaN(measurement)) 21 | return "Unknown"; 22 | return "Acceptable"; 23 | } 24 | return "Too high"; 25 | } 26 | return "Too low"; 27 | } 28 | 29 | static string ObterEstacaoDoAno(DateTime data) => data.Month switch 30 | { 31 | >= 3 and < 6 => "Outono", 32 | >= 6 and < 9 => "Inverno", 33 | >= 9 and < 12 => "Primavera", 34 | 12 or (>= 1 and < 3) => "Verão", 35 | _ => throw new ArgumentOutOfRangeException(nameof(data), $"Data inesperada: {data.Month}."), 36 | }; 37 | 38 | static string ObterEstacaoDoAnoCompiled(DateTime data) 39 | { 40 | switch (data.Month) 41 | { 42 | case 3: 43 | case 4: 44 | case 5: 45 | return "Outono"; 46 | case 6: 47 | case 7: 48 | case 8: 49 | return "Inverno"; 50 | case 9: 51 | case 10: 52 | case 11: 53 | return "Primavera"; 54 | case 1: 55 | case 2: 56 | case 12: 57 | return "Verão"; 58 | default: 59 | throw new ArgumentOutOfRangeException(nameof(data), $"Data inesperada: {data.Month}."); 60 | } 61 | } 62 | 63 | static string TakeFive(object input) => input switch 64 | { 65 | string { Length: >= 5 } s => s.Substring(0, 5), 66 | string s => s, 67 | ICollection { Count: >= 5 } symbols => new string(symbols.Take(5).ToArray()), 68 | ICollection symbols => new string(symbols.ToArray()), 69 | null => throw new ArgumentNullException(nameof(input)), 70 | _ => throw new ArgumentException("Not supported input type."), 71 | }; 72 | } 73 | -------------------------------------------------------------------------------- /LinqNaoExiste.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Linq.Expressions; 3 | using System.Reflection; 4 | 5 | namespace NonEcsiste.LinqNaoExiste; 6 | 7 | public class LinqNaoExiste 8 | { 9 | public static void LinqToObjects() 10 | { 11 | var ns = new[] { 1, 2, 3 }; 12 | var maioresQue1 = from n in ns 13 | where n > 1 14 | select n; 15 | // como se fosse: 16 | // var maioresQue1 = Enumerable.Where(ns, n => n > 1); 17 | foreach (var n in maioresQue1) 18 | WriteLine(n); 19 | } 20 | public static void LinqToGiggio() 21 | { 22 | var pessoas = ObterPessoas(); 23 | var famigliaBassi = from n in pessoas 24 | where n.SobreNome == "Bassi" 25 | select n; 26 | // quase como se fosse: 27 | // ParameterExpression pessoaParameter = Expression.Parameter(typeof(Pessoa), "n"); 28 | // var famigliaBassi = Queryable.Where(pessoas, 29 | // Expression.Lambda>( 30 | // Expression.Equal(Expression.Property(pessoaParameter, Pessoa.SobreNome), 31 | // Expression.Constant("Bassi", typeof(string))), [pessoaParameter])); 32 | foreach (var pessoa in famigliaBassi) 33 | WriteLine(pessoa); 34 | } 35 | 36 | static IQueryable ObterPessoas() 37 | { 38 | var pessoas = new[] 39 | { 40 | new Pessoa { Nome = "Giovanni", SobreNome = "Bassi" }, 41 | new Pessoa { Nome = "João", SobreNome = "Silva" } 42 | }; 43 | return new PessoaQuery(new PessoaQueryProvider(pessoas)); 44 | } 45 | } 46 | 47 | public class Pessoa 48 | { 49 | public string Nome { get; set; } 50 | public string SobreNome { get; set; } 51 | public override string ToString() => $"{Nome} {SobreNome}"; 52 | } 53 | 54 | #region Linq provider 55 | public class PessoaQueryProvider : IQueryProvider 56 | { 57 | private readonly IEnumerable pessoas; 58 | 59 | public PessoaQueryProvider(IEnumerable pessoas) => this.pessoas = pessoas ?? throw new ArgumentNullException(nameof(pessoas)); 60 | 61 | public IQueryable CreateQuery(Expression expression) => new PessoaQuery(this, expression); 62 | 63 | public IQueryable CreateQuery(Expression expression) => new PessoaQuery(this, expression); 64 | 65 | public TElement Execute(Expression expression) => (TElement)Execute(expression); 66 | 67 | public static string GetQueryText(Expression expression) => "pessoas"; // todo 68 | 69 | public object Execute(Expression expression) => new PessoaQueryTranslator().Translate(pessoas, expression); 70 | } 71 | 72 | public class PessoaQuery : IQueryable, IQueryable, IEnumerable, IEnumerable, IOrderedQueryable, IOrderedQueryable 73 | { 74 | PessoaQueryProvider provider; 75 | Expression expression; 76 | 77 | public PessoaQuery(PessoaQueryProvider provider) 78 | { 79 | this.provider = provider ?? throw new ArgumentNullException("provider"); 80 | expression = Expression.Constant(this); 81 | } 82 | 83 | public PessoaQuery(PessoaQueryProvider provider, Expression expression) 84 | { 85 | this.provider = provider ?? throw new ArgumentNullException("provider"); 86 | this.expression = expression ?? throw new ArgumentNullException("expression"); 87 | if (!typeof(IQueryable).IsAssignableFrom(expression.Type)) 88 | throw new ArgumentOutOfRangeException("expression"); 89 | } 90 | 91 | Expression IQueryable.Expression => expression; 92 | 93 | Type IQueryable.ElementType => typeof(T); 94 | 95 | IQueryProvider IQueryable.Provider => provider; 96 | 97 | public IEnumerator GetEnumerator() => ((IEnumerable)provider.Execute(expression)).GetEnumerator(); 98 | 99 | IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)provider.Execute(expression)).GetEnumerator(); 100 | } 101 | 102 | public class PessoaQueryTranslator : ExpressionVisitor 103 | { 104 | private IEnumerable pessoas; 105 | 106 | public IEnumerable Translate(IEnumerable pessoas, Expression expression) 107 | { 108 | this.pessoas = pessoas; 109 | Visit(expression); 110 | return this.pessoas; 111 | } 112 | 113 | protected override Expression VisitMethodCall(MethodCallExpression m) 114 | { 115 | if (m.Method.DeclaringType == typeof(Queryable) && m.Method.Name == "Where") 116 | { 117 | var lambda = (LambdaExpression)StripQuotes(m.Arguments[1]); 118 | Visit(lambda.Body); 119 | return m; 120 | } 121 | throw new NotSupportedException($"The method '{m.Method.Name}' is not supported"); 122 | } 123 | 124 | protected override Expression VisitBinary(BinaryExpression b) 125 | { 126 | switch (b.NodeType) 127 | { 128 | case ExpressionType.Equal: 129 | if (b.Left.NodeType == ExpressionType.MemberAccess && b.Left is MemberExpression memberExpression) 130 | { 131 | if (b.Right.NodeType == ExpressionType.Constant) 132 | { 133 | var property = memberExpression.Member.Name; 134 | if (property == "SobreNome") 135 | { 136 | var sobreNome = (string)((ConstantExpression)b.Right).Value; 137 | var list = new List(); 138 | foreach (var p in pessoas) 139 | if (p.SobreNome == sobreNome) 140 | list.Add(p); 141 | pessoas = list; 142 | } 143 | else 144 | { 145 | throw new NotSupportedException($"Can't resolve operations on property '{property}'"); 146 | } 147 | } 148 | else 149 | { 150 | throw new NotSupportedException($"Can't resolve operations on right type '{b.Right.NodeType}'"); 151 | } 152 | } 153 | else 154 | { 155 | throw new NotSupportedException($"Can't resolve operations on left node type '{b.Left.NodeType}'"); 156 | } 157 | break; 158 | default: 159 | throw new NotSupportedException($"The binary operator '{b.NodeType}' is not supported"); 160 | } 161 | return b; 162 | } 163 | 164 | private static Expression StripQuotes(Expression e) 165 | { 166 | while (e.NodeType == ExpressionType.Quote) 167 | e = ((UnaryExpression)e).Operand; 168 | return e; 169 | } 170 | } 171 | #endregion 172 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | 33 | # Visual Studio 2015/2017 cache/options directory 34 | .vs/ 35 | # Uncomment if you have tasks that create the project's static files in wwwroot 36 | #wwwroot/ 37 | 38 | # Visual Studio 2017 auto generated files 39 | Generated\ Files/ 40 | 41 | # MSTest test Results 42 | [Tt]est[Rr]esult*/ 43 | [Bb]uild[Ll]og.* 44 | 45 | # NUnit 46 | *.VisualState.xml 47 | TestResult.xml 48 | nunit-*.xml 49 | 50 | # Build Results of an ATL Project 51 | [Dd]ebugPS/ 52 | [Rr]eleasePS/ 53 | dlldata.c 54 | 55 | # Benchmark Results 56 | BenchmarkDotNet.Artifacts/ 57 | 58 | # .NET Core 59 | project.lock.json 60 | project.fragment.lock.json 61 | artifacts/ 62 | 63 | # StyleCop 64 | StyleCopReport.xml 65 | 66 | # Files built by Visual Studio 67 | *_i.c 68 | *_p.c 69 | *_h.h 70 | *.ilk 71 | *.meta 72 | *.obj 73 | *.iobj 74 | *.pch 75 | *.pdb 76 | *.ipdb 77 | *.pgc 78 | *.pgd 79 | *.rsp 80 | *.sbr 81 | *.tlb 82 | *.tli 83 | *.tlh 84 | *.tmp 85 | *.tmp_proj 86 | *_wpftmp.csproj 87 | *.log 88 | *.vspscc 89 | *.vssscc 90 | .builds 91 | *.pidb 92 | *.svclog 93 | *.scc 94 | 95 | # Chutzpah Test files 96 | _Chutzpah* 97 | 98 | # Visual C++ cache files 99 | ipch/ 100 | *.aps 101 | *.ncb 102 | *.opendb 103 | *.opensdf 104 | *.sdf 105 | *.cachefile 106 | *.VC.db 107 | *.VC.VC.opendb 108 | 109 | # Visual Studio profiler 110 | *.psess 111 | *.vsp 112 | *.vspx 113 | *.sap 114 | 115 | # Visual Studio Trace Files 116 | *.e2e 117 | 118 | # TFS 2012 Local Workspace 119 | $tf/ 120 | 121 | # Guidance Automation Toolkit 122 | *.gpState 123 | 124 | # ReSharper is a .NET coding add-in 125 | _ReSharper*/ 126 | *.[Rr]e[Ss]harper 127 | *.DotSettings.user 128 | 129 | # JustCode is a .NET coding add-in 130 | .JustCode 131 | 132 | # TeamCity is a build add-in 133 | _TeamCity* 134 | 135 | # DotCover is a Code Coverage Tool 136 | *.dotCover 137 | 138 | # AxoCover is a Code Coverage Tool 139 | .axoCover/* 140 | !.axoCover/settings.json 141 | 142 | # Visual Studio code coverage results 143 | *.coverage 144 | *.coveragexml 145 | 146 | # NCrunch 147 | _NCrunch_* 148 | .*crunch*.local.xml 149 | nCrunchTemp_* 150 | 151 | # MightyMoose 152 | *.mm.* 153 | AutoTest.Net/ 154 | 155 | # Web workbench (sass) 156 | .sass-cache/ 157 | 158 | # Installshield output folder 159 | [Ee]xpress/ 160 | 161 | # DocProject is a documentation generator add-in 162 | DocProject/buildhelp/ 163 | DocProject/Help/*.HxT 164 | DocProject/Help/*.HxC 165 | DocProject/Help/*.hhc 166 | DocProject/Help/*.hhk 167 | DocProject/Help/*.hhp 168 | DocProject/Help/Html2 169 | DocProject/Help/html 170 | 171 | # Click-Once directory 172 | publish/ 173 | 174 | # Publish Web Output 175 | *.[Pp]ublish.xml 176 | *.azurePubxml 177 | # Note: Comment the next line if you want to checkin your web deploy settings, 178 | # but database connection strings (with potential passwords) will be unencrypted 179 | *.pubxml 180 | *.publishproj 181 | 182 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 183 | # checkin your Azure Web App publish settings, but sensitive information contained 184 | # in these scripts will be unencrypted 185 | PublishScripts/ 186 | 187 | # NuGet Packages 188 | *.nupkg 189 | # NuGet Symbol Packages 190 | *.snupkg 191 | # The packages folder can be ignored because of Package Restore 192 | **/[Pp]ackages/* 193 | # except build/, which is used as an MSBuild target. 194 | !**/[Pp]ackages/build/ 195 | # Uncomment if necessary however generally it will be regenerated when needed 196 | #!**/[Pp]ackages/repositories.config 197 | # NuGet v3's project.json files produces more ignorable files 198 | *.nuget.props 199 | *.nuget.targets 200 | 201 | # Microsoft Azure Build Output 202 | csx/ 203 | *.build.csdef 204 | 205 | # Microsoft Azure Emulator 206 | ecf/ 207 | rcf/ 208 | 209 | # Windows Store app package directories and files 210 | AppPackages/ 211 | BundleArtifacts/ 212 | Package.StoreAssociation.xml 213 | _pkginfo.txt 214 | *.appx 215 | *.appxbundle 216 | *.appxupload 217 | 218 | # Visual Studio cache files 219 | # files ending in .cache can be ignored 220 | *.[Cc]ache 221 | # but keep track of directories ending in .cache 222 | !?*.[Cc]ache/ 223 | 224 | # Others 225 | ClientBin/ 226 | ~$* 227 | *~ 228 | *.dbmdl 229 | *.dbproj.schemaview 230 | *.jfm 231 | *.pfx 232 | *.publishsettings 233 | orleans.codegen.cs 234 | 235 | # Including strong name files can present a security risk 236 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 237 | #*.snk 238 | 239 | # Since there are multiple workflows, uncomment next line to ignore bower_components 240 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 241 | #bower_components/ 242 | 243 | # RIA/Silverlight projects 244 | Generated_Code/ 245 | 246 | # Backup & report files from converting an old project file 247 | # to a newer Visual Studio version. Backup files are not needed, 248 | # because we have git ;-) 249 | _UpgradeReport_Files/ 250 | Backup*/ 251 | UpgradeLog*.XML 252 | UpgradeLog*.htm 253 | ServiceFabricBackup/ 254 | *.rptproj.bak 255 | 256 | # SQL Server files 257 | *.mdf 258 | *.ldf 259 | *.ndf 260 | 261 | # Business Intelligence projects 262 | *.rdl.data 263 | *.bim.layout 264 | *.bim_*.settings 265 | *.rptproj.rsuser 266 | *- [Bb]ackup.rdl 267 | *- [Bb]ackup ([0-9]).rdl 268 | *- [Bb]ackup ([0-9][0-9]).rdl 269 | 270 | # Microsoft Fakes 271 | FakesAssemblies/ 272 | 273 | # GhostDoc plugin setting file 274 | *.GhostDoc.xml 275 | 276 | # Node.js Tools for Visual Studio 277 | .ntvs_analysis.dat 278 | node_modules/ 279 | 280 | # Visual Studio 6 build log 281 | *.plg 282 | 283 | # Visual Studio 6 workspace options file 284 | *.opt 285 | 286 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 287 | *.vbw 288 | 289 | # Visual Studio LightSwitch build output 290 | **/*.HTMLClient/GeneratedArtifacts 291 | **/*.DesktopClient/GeneratedArtifacts 292 | **/*.DesktopClient/ModelManifest.xml 293 | **/*.Server/GeneratedArtifacts 294 | **/*.Server/ModelManifest.xml 295 | _Pvt_Extensions 296 | 297 | # Paket dependency manager 298 | .paket/paket.exe 299 | paket-files/ 300 | 301 | # FAKE - F# Make 302 | .fake/ 303 | 304 | # CodeRush personal settings 305 | .cr/personal 306 | 307 | # Python Tools for Visual Studio (PTVS) 308 | __pycache__/ 309 | *.pyc 310 | 311 | # Cake - Uncomment if you are using it 312 | # tools/** 313 | # !tools/packages.config 314 | 315 | # Tabs Studio 316 | *.tss 317 | 318 | # Telerik's JustMock configuration file 319 | *.jmconfig 320 | 321 | # BizTalk build output 322 | *.btp.cs 323 | *.btm.cs 324 | *.odx.cs 325 | *.xsd.cs 326 | 327 | # OpenCover UI analysis results 328 | OpenCover/ 329 | 330 | # Azure Stream Analytics local run output 331 | ASALocalRun/ 332 | 333 | # MSBuild Binary and Structured Log 334 | *.binlog 335 | 336 | # NVidia Nsight GPU debugger configuration file 337 | *.nvuser 338 | 339 | # MFractors (Xamarin productivity tool) working folder 340 | .mfractor/ 341 | 342 | # Local History for Visual Studio 343 | .localhistory/ 344 | 345 | # BeatPulse healthcheck temp database 346 | healthchecksdb 347 | 348 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 349 | MigrationBackup/ 350 | 351 | # Ionide (cross platform F# VS Code tools) working folder 352 | .ionide/ 353 | --------------------------------------------------------------------------------