|
Because C# is a strongly-typed langrage which is compiled. The compiler must "know" the Type of any value, or object, created ... before compilation.
The (shortcut) use of var to hold a result, as in this example: var mystudent = new Student(); ...
Will work because the compiler can infer the Type from the right hand side of the assignment.
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
|
|
|
|
|
BillWoodruff wrote: var mystudent = new Student();
On a similar note, from C# 9 onwards, the compiler can often infer the type on the right-hand side from the declaration:
Target-typed new expressions - C# 9.0 draft specifications | Microsoft Learn[^]
Student student = new(); That works in more places than var (eg: fields), and can reduce the amount of typing even further; for example, compare:
var students = new List<Student>
{
new Student { ... },
new Student { ... },
}; to:
List<Student> students = new()
{
new() { ... },
new() { ... },
};
However, I suspect the use of var and target-typed new might currently be a few lessons further down the line for the OP.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
thanks, when i was teaching, i "forced" my students to specify Type explicitly the newer uses of thing like discards make me dizzy, use of new() makes me nauseous
ReSharper has gotten better and better at controlling use of 'var: [^]
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
|
|
|
|
|
As so many commentators at the World Cup have suggested, it is time to stop using VAR.
|
|
|
|
|
i am completely baffled world cup <=> to var ?
(on strong meds, brain fogged) bill
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
|
|
|
|
|
VAR stands for Video Assistant Referee, and lately has caused some very controversial decisions.
|
|
|
|
|
Message Closed
modified 29-Nov-22 8:40am.
|
|
|
|
|
You need to remove it the same way you removed it from the common list. Remember, after the two calls to AddRange you have three separate lists, so what you do to one list does not have any effect on the others.
|
|
|
|
|
To add to what Richard has said, the important thing here is the keyword new
When you create a new instance of any class, that is exactly what you get: a brand new, totally separate instance of the class which has nothing at all to do with any other. Think about it: if you put your mobile in the glovebox of your car, then go and buy a new vehicle, would your mobile be in it's glovebox? Of course not - you understand that the two cars are separate, and whatever you do to the first one has no affect whatsoever on the second! Indeed, life would get very odd if it was otherwise!
So when you do this:
List<int> a = new List<int>();
List<int> b = new List<int>();
List<int> c = new List<int>(); you create three independent collections: whatever you do to one has no affect on the others. When you add items to a collection a "copy" of the value is added so when you remove them, only that local copy gets removed.
If instead of integers you used a class, then a copy of the reference to that class instance is added, so if a class exists in two collections, then changing it's content via either collection effects the same instance:
public class MyClass
{
public int X { get; set; }
}
private void MyButton_Click(object sender, EventArgs e)
{
List<MyClass> a = new List<MyClass>();
List<MyClass> b = new List<MyClass>();
MyClass mc = new MyClass() { X = 1 };
a.Add(mc);
b.Add(mc);
foreach (MyClass m in a)
{
m.X += 10;
}
foreach (MyClass m in b)
{
m.X += 100;
}
Console.WriteLine(mc.X);
}
Will print "111" because the same instance is accessed from both collections.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Require assistance with a code example to be able to broadcast a simple message from an application to many instances of that application on the same computer. The message consists of a single string, either 1/0, On/Off, Start/Stop, High/Low or True/False broadcast from the Master application on 127.0.0.1:1234. The transmitting application (Master) shall continuously send the message until application close. The receiving application/s (Slaves) shall also receive the message continuously on a separate thread until the Slave application is closed. Timing is important, and needs to be less than 8 milliseconds, which I suspect will not be a problem.
The application is a VS 2019 WinForm type under dotNet 4.7, and the code snippet on the Master application shall be activated by a command button. The Slave/s will activate the appropriate code when either of the two conditions are meet.
As a retiree who last programmed in the 90's under Visual Studio 6, it's has been a leap to Visual Studio 2019 C#, and a lot of fun. But networking alludes me at this time. Appreciate any help on offer. With thanks.
|
|
|
|
|
Generally, client - server connections are point to point so that server can direct responses to the originating client only.
The way I'd probably do it is via Sockets: the app starts and tries to talk to a server instance. If it can, it's a client.
If it can't, it starts a server Socket and waits for a connection. When it gets it, that gets added to a Clients collection, and a new Socket waits for another connection.
When a socket closes, it's removed from the collection.
Broadcast is then simple: iterate the collection and send to each.
Make sense?
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Oh My! That is way past my understanding OriginalGriff. Hence the request for the very simple code example Back in a day, the Server was in charge of all things, but if I understand correctly that is the role of the client. Broadcast Messaging does not occur until two or more sockets are open? It that correct? I thought that the term 'broadcast' to be sending out data even if no one is listening.
I had a look through the various examples on-line, and found them overly complicated for my simple needs, but in hindsight, I suspect this is all necessary. Appreciate the reply. Perhaps more searching is in order.
|
|
|
|
|
Start with an example using one server and one client. You will find examples of this.
Then test sending your messages.
You might even build it out completely using just a single client.
Then finally add the collection as per the previous suggestion. You probably can find examples of this also.
|
|
|
|
|
|
Thanks Richard for the reply. Will have a look though the Named Pipes example you offered.
|
|
|
|
|
Use Sockets to send and receive data over TCP - .NET | Microsoft Learn
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
Thanks Guys. Appreciated. All good with the replies. Job done.
|
|
|
|
|
i am using OleDbConnection to read excel files.
excel file is read properly.
but my form is resize and all text looks bigger and buggy when i open the connection.
i really dont understand whats happend.
please help me for this.
thanks in advance.
DataTable sheet1 = new DataTable("Excel Sheet");
OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
csbuilder.DataSource = filename;
csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
string selectSql = @"SELECT * FROM [Sheet1$]";
using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
{
connection.Open();
adapter.Fill(sheet1);
connection.Close();
}
|
|
|
|
|
Inherently, there's nothing in there that would cause the UI to resize. I assume, however, that there is a lot more to your code than this - what do you do with the DataTable? Is this being bound to something on the form?
|
|
|
|
|
I know about the ConcurrentBag, ConcurrentDictionary, ConcurrentQueue and ConcurrentStack collection classes. But is there any Concurrent equivalent to the good ol' List<>?
The ConcurrentBag says it provides a thread safe unordered collection, but I need an ordered collection.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
There's a discussion about adding a concurrent list here:
ConcurrentList<T> · Issue #41740 · dotnet/runtime · GitHub[^]
The conclusion is that there's no meaningful way to implement it without locking the entire list - at which point, you might was well wrap a regular List<T> with locks.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you for the reply, Richard.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
A concurrent dictionary loaded ordered is essentially an ordered list.
Whether you handle it as KeyValue pairs or as .Values is another matter (maybe).
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
Yeah, that's what I've settled on doing - using ConcurrentDictionary's.
Thanks for your reply.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
I'm using EF 6 Core Code First. I'm trying to set up some basic code and I'm getting an exception at runtime.
Here's my Context class:
using Microsoft.EntityFrameworkCore;
namespace EFCoreDBFirstExample.Models
{
public partial class ModelContext : DbContext
{
public virtual DbSet Departments { get; set; }
public virtual DbSet Employees { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionString = @"Server=MAROIS_KEVIN_1\SQLEXPRESS;Database=Test;Trusted_Connection=true;Encrypt=false;";
optionsBuilder.UseSqlServer(connectionString, options => options.EnableRetryOnFailure());
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity(entity =>
{
entity.ToTable("Departments", "public");
entity.HasKey(e => e.DepartmentId)
.HasName("DeptartmentId");
entity.Property(e => e.DepartmentId)
.HasColumnName("DeptartmentId");
entity.Property(e => e.DepartmentName)
.HasColumnName("DepartmentName")
.HasColumnType("varchar")
.HasMaxLength(30);
});
modelBuilder.Entity(entity =>
{
entity.ToTable("EmployeeName", "public");
entity.HasKey(e => e.EmployeeId)
.HasName("EmployeeId");
entity.Property(e => e.EmployeeId)
.HasColumnName("EmployeeId");
entity.Property(e => e.EmployeeName)
.HasColumnName("EmployeeName")
.HasColumnType("varchar")
.HasMaxLength(30);
});
}
}
}
Here's how I'm using it
using EFCoreDBFirstExample.Models;
using (var db = new ModelContext())
{
var newDept = new Departments();
newDept.DepartmentId = 1;
newDept.DepartmentName = "Development";
db.Departments.Add(newDept);
var count = db.SaveChanges();
Console.WriteLine("{0} records saved to database", count);
Console.WriteLine();
Console.WriteLine("Departments:");
foreach (var dept in db.Departments)
{
Console.WriteLine($"{dept.DepartmentId}: {dept.DepartmentName}" );
}
Console.ReadLine();
}
Here's the exception:
Microsoft.EntityFrameworkCore.Storage.RetryLimitExceededException
HResult=0x80131500
Message=The maximum number of retries (6) was exceeded while executing database operations with 'SqlServerRetryingExecutionStrategy'. See the inner exception for the most recent failure.
Inner Exception 1:
SqlException: Cannot open database "Test" requested by the login. The login failed.
Login failed for user 'MAROIS_KEVIN_1\kevin'.
As you can see, I'm using Trusted Connection in my connection string. Not sure why EF is trying to connect with the user 'kevin'.
I could use some help here. Thanks
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|