惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
博客园 - 【当耐特】
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
aimingoo的专栏
aimingoo的专栏
WordPress大学
WordPress大学
G
Google Developers Blog
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
P
Proofpoint News Feed
J
Java Code Geeks
U
Unit 42
云风的 BLOG
云风的 BLOG
阮一峰的网络日志
阮一峰的网络日志
N
Netflix TechBlog - Medium
宝玉的分享
宝玉的分享
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
D
Docker
V
Visual Studio Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Help Net Security
V
V2EX
T
Tailwind CSS Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Ref, Out & In - C#
Mirza Leka · 2026-06-20 · via DEV Community
Cover image for Ref, Out & In - C#

Mirza Leka

In C#, ref, out, and in are keywords used to pass arguments to methods by reference rather than by value.

Passing variables by reference

Consider this. We want to modify a local variable in the SetFullName() method:

        private static void SetFullName(string nameToSet)
        {
            nameToSet = "Mirza Leka";
        }

But the SetFullName() method does not return the modified name. Thus, when we invoke the method from the outside, the calling method still has the old name.

    internal class Program
    {
        static void Main(string[] args)
        {
            var name = "Mirza";

            SetFullName(name);

            Console.WriteLine(name); // "Mirza"

            Console.ReadLine();
        }

        private static void SetFullName(string nameToSet)
        {
            nameToSet = "Mirza Leka";
        }

    }

How do we get around that? How do we get back the modified name without explicitly returning the name as follows:

        // common practice
        private static string GetFullName(string nameToSet)
        {
            nameToSet = "Mirza Leka";
            return nameToSet;
        }

Ref

The ref keyword allows a variable to be passed by reference to other methods.

        private static void SetFullName(ref string nameToSet)
        {
            nameToSet = "Mirza Leka";
        }

With ref in place, any changes made to the name will be visible in the calling method:

    internal class Program
    {
        static void Main(string[] args)
        {
            var name = "Mirza";

            SetFullName(ref name);

            Console.WriteLine(name); // "Mirza Leka"

            Console.ReadLine();
        }

        private static void SetFullName(string nameToSet)
        {
            nameToSet = "Mirza Leka";
        }

    }

Pros & Cons:

  • ✅ Let's use a method to modify the caller's variable directly, without needing to return it.
  • ✅ Avoids copying large structs into the method.
  • ❌ The variable must be initialized before it's passed in.

Quick note: We do not need to use the ref keyword when passing variables that are reference types.

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            var person = new Person { Id = 1, Name = name };

            SetFullName(person);

            Console.WriteLine(person.Name); // "Mirza Leka"

            Console.ReadLine();
        }

        private static void SetFullName(Person p)
        {
            p.Name = "Mirza Leka";
        }
    }

Read-Only arguments

Say we want to create a logging method that can only read the name variable, but cannot modify it. That's where the in keyword comes in.

When you set the in next to the argument, it signals to the compiler that the parameter is read-only.

        private static void LogFullName(in string nameToLog)
        {
            Console.WriteLine(nameToLog);
        }

    internal class Program
    {
        static void Main(string[] args)
        {

            var name = "Mirza";

            LogFullName(name);  // "Mirza"

            Console.ReadLine();
        }

        private static void LogFullName(in string nameToLog)
        {
            Console.WriteLine(nameToLog);
        }

    }

Modifications aren't allowed.

        private static void LogFullName(in string nameToLog)
        {
            //nameToLog = "Mirza Leka"; ❌
            Console.WriteLine(nameToLog);
        }

Pros & Cons:

  • ✅ Avoids copying large structs into the method, the same way ref does, but without allowing the method to mutate them.
  • ✅ Makes intent explicit — readers know the argument is read-only inside the method.
  • ❌ Only prevents reassigning the parameter itself. If it's a reference type, its members can still be mutated.

More than one return

Ever been in a situation where you wanted to add a response without changing the original return type?

Out

The out keyword lets us do just that - let the method return more than one response.

        private static bool IsValidName(string name, out string errorMessage)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                errorMessage = "Name must be set!";
                return false;
            }

            errorMessage = string.Empty;
            return true;
        }

The IsValid() method will still return a boolean, but we can also extract the error.

            var isValid = IsValidName(name, out string errorMsg);

Now we can both validate the response and get the error message.

    internal class Program
    {
        static void Main(string[] args)
        {
            var name = "Mirza";

            var isValid = IsValidName(name, out string errorMsg);

            if (!isValid)
            {
                Console.WriteLine($"Error: {errorMsg}");
            }
            else
            {
                Console.WriteLine(name);
            }

            Console.ReadLine();
        }
    }

Pros & Cons:

  • ✅ A method can return multiple values without creating a custom return type (class or tuple).
  • ✅ Commonly used in the validate-and-get-result pattern (like TryParse, TryGetValue).
  • ❌ The parameter must be assigned inside the method before it returns.

Summary

Three keywords. Three questions to answer:

  • ref — does the method need to change the value, and should that change be visible to the caller?
  • in — do you pass a value type and want to keep it read-only?
  • out — does the method need to return more than one value?

Until next time 👋