Declare class in one line #1659
-
Sometimes we use really simple classes to demenstrate simple concepts and they contain only one method or field. Instead of this public class Foo
{
public void Bar() => Console.WriteLine("Bar");
} we can do this public class Foo => public void Bar() => Console.WriteLine("Bar"); And instead of public class Foo
{
public void Bar() => Console.WriteLine("Bar");
public int Baz() => Console.WriteLine("Baz");
} this: public class Foo => public void Bar() => Console.WriteLine("Bar");, public int Baz() => Console.WriteLine("Baz");; Ediit added implimentations |
Beta Was this translation helpful? Give feedback.
Replies: 9 comments
-
@lazyloader Not even the first example could be legal C# since non-abstract methods must declare bodies. |
Beta Was this translation helpful? Give feedback.
-
@jnm2 there, added implimentations |
Beta Was this translation helpful? Give feedback.
-
Why is:
better than public class Foo { public void Bar() => Console.WriteLine("Bar"); } AFAICT, you save 1 character... |
Beta Was this translation helpful? Give feedback.
-
This case is even weirder: public class Foo => public void Bar() => Console.WriteLine("Bar");, public int Baz() => Console.WriteLine("Baz");; Because you can already write: public class Foo { public void Bar() => Console.WriteLine("Bar"); public int Baz() => Console.WriteLine("Baz"); } Which is one character fewer! So your 'declare class in one line' proposal actually takes up more space :) |
Beta Was this translation helpful? Give feedback.
-
@lazyloader Now that you've added method bodies, it shows that each of the examples is harder to read than the equivalent multiline syntax. And that's just when every method has a very simple body. Depending on what you're doing, you might be interested in https://github.com/dotnet/csharplang/blob/master/proposals/records.md#records though. I definitely am! |
Beta Was this translation helpful? Give feedback.
-
@CyrusNajmabadi Couldn't you have made the same arguement for expression body methods? public void Foo()
{
Console.WriteLine("Foo");
} Written as public void Foo() { Console.WriteLine("Foo"); } So why bother with public void Foo() => Console.WriteLine("Foo"); It's cleaner and easier to read, and almost no one declares a function with everything on one line unless they're using Also |
Beta Was this translation helpful? Give feedback.
-
Yes. Bu that wasn't the argument for Expression-Body methods. Expression-body methods came from the fact that we'd already done public int Foo => whatever; Instead of public int Foo { get { return whatever; } } Once we already had -- So the argument was never "let's reduce methods from -- Also, the 'void' version of |
Beta Was this translation helpful? Give feedback.
-
F# record style declarations would be nice. |
Beta Was this translation helpful? Give feedback.
Why is:
better than
AFAICT, you save 1 character...